Skip to content

Commit

Permalink
Add get_json Twig function
Browse files Browse the repository at this point in the history
  • Loading branch information
samwilson committed Oct 22, 2023
1 parent 15d234c commit f10f83d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
2 changes: 2 additions & 0 deletions docs/content/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ these are explained on this page.
See the example in [/example/templates/tag.html.twig](https://github.com/samwilson/basildon/blob/main/example/templates/tag.html.twig)
6. `wikipedia(lang, title)` — Returns an HTML extract of the given article.
For example: `{{wikipedia('en', 'Tag (metadata)')|raw}}`
7. `get_json(url)` — Fetch JSON data from any URL.
For example: `{{get_json('https://api.wikitree.com/api.php?action=getProfile&key=Hall-22337')}}`

## Filters and escapers

Expand Down
4 changes: 4 additions & 0 deletions example/templates/recent.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

{{ page.body|md2html|raw }}

{% set example_data = get_json('https://microsoftedge.github.io/Demos/json-dummy-data/64KB.json') %}

<p>Example description: {{example_data.3.bio}}</p>

<ol>
{% for p in database.query('SELECT * FROM pages WHERE date IS NOT NULL ORDER BY date DESC LIMIT 10') %}
<li>
Expand Down
24 changes: 24 additions & 0 deletions src/Twig.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ public function getFunctions(): array
new TwigFunction('date_create', [$this, 'functionDateCreate']),
new TwigFunction('strtotime', 'strtotime'),
new TwigFunction('json_decode', 'json_decode'),
new TwigFunction('get_json', [$this, 'functionGetJson']),
new TwigFunction('tex_url', [$this, 'functionTexUrl']),
new TwigFunction('wikidata', [$this, 'functionWikidata']),
new TwigFunction('commons', [$this, 'functionCommons']),
Expand Down Expand Up @@ -326,6 +327,29 @@ public function functionWikipedia(string $lang, string $articleTitle): string
return self::$data['commons'][$articleTitle];
}

public function functionGetJson(string $url): mixed
{
$cacheKey = md5($url);
if (isset(self::$data['json'][$cacheKey])) {
return self::$data['json'][$cacheKey];
}
$cache = $this->getCachePool('json');
$cacheItem = $cache->getItem($cacheKey);
if ($cacheItem->isHit()) {
return $cacheItem->get();
}
CommandBase::writeln("Get JSON: $url");
$json = (new Client())->get($url)->getBody()->getContents();
$response = json_decode($json, true);
if (!$response) {
throw new Exception("Unable to get JSON from URL: $url");
}
self::$data['commons'][$cacheKey] = $response;
$cacheItem->set(self::$data['commons'][$cacheKey]);
$cache->save($cacheItem);
return self::$data['commons'][$cacheKey];
}

/**
* @return string Relative URL string, of the form '/assets/qrcodes/hash.svg'.
*/
Expand Down

0 comments on commit f10f83d

Please sign in to comment.