我想从Twig服务中检索JSON,并将其合并到Twig模板中。
我翻阅了文档,发现我可以使用这个选项。
我遵循了文档中的步骤,并编写了这个插件:
/var/www/html/grav/user/plugins/category# ls
category.php category.yaml twig/var/www/html/grav/user/plugins/category# cat category.yaml
enabled: true/var/www/html/grav/user/plugins/category# cat category.php
<?php
namespace Grav\Plugin;
use \Grav\Common\Plugin;
class CategoryPlugin extends Plugin
{
public static function getSubscribedEvents()
{
return [
'onTwigExtensions' => ['onTwigExtensions', 0]
];
}
public function onTwigExtensions()
{
require_once(__DIR__ . '/twig/CategoryTwigExtension.php');
$this->grav['twig']->twig->addExtension(new CategoryTwigExtension());
}
}/var/www/html/grav/user/plugins/category# cat twig/CategoryTwigExtension.php
<?php
namespace Grav\Plugin;
class CategoryTwigExtension extends \Twig_Extension
{
public function getName()
{
return 'CategoryTwigExtension';
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('get_child_category', [$this, 'getChildCategoryFunction'])
];
}
public function getChildCategoryFunction()
{
$json = file_get_contents('http://localhost:8888/get_child_category/2/es_ES');
$obj = json_decode($json);
return $json;
}
}然后,我将以下函数调用合并到Twig模板中:
{{ get_child_category() }}但是:
$json字符串,但是如何传递整个JSON数据并单独检索字段呢?就我而言,如果我用:
<span>{{ get_child_category() }}</span>在Twig中,我得到以下字符串:
[{"id": 11, "name": "Racoons"}, {"id": 10, "name": "Cats"}]我将如何访问Twig中的单个记录,包括对JSON数组的迭代和对每个记录的单独字段提取(id,name)?
发布于 2018-03-02 05:17:30
您的函数返回一个数组。你需要迭代一遍。下面是Grav文档中的一个示例。
<ul>
{% for cookie in cookies %}
<li>{{ cookie.flavor }}</li>
{% endfor %}
</ul>示例中的简单名称列表是一个简单的编辑。
<ul>
{% for child in get_child_category() %}
<li>{{ child.name }}</li>
{% endfor %}
</ul>https://stackoverflow.com/questions/49028474
复制相似问题