php - 在 Twig 中解码 JSON

标签 php symfony twig

是否可以在 twig 中解码 JSON?谷歌搜索似乎对此没有任何结果。在 Twig 中解码 JSON 没有意义吗?


我正在尝试访问 Symfony2 的实体字段类型 ( Entity Field Type) 上的 2 个实体属性。

在遇到之前的 2 个 SO 问题(Symfony2 entity field type alternatives to "property" or "__toString()"?Symfony 2 Create a entity form field with 2 properties)建议向实体添加一个额外的方法来检索自定义字符串而不是实体属性后,我想到(并且确实)返回了一个 JSON 字符串表示一个对象实例。

实体类中的某处:

/**
 * Return a JSON string representing this class.
 */
public function getJson()
{
   return json_encode(get_object_vars($this));
}

并且在表单中(类似的东西):

$builder->add('categories', 'entity', array (
...
'property' => 'json',
...
));

之后,我希望在 Twig 中对其进行 json_decode...

{% for category in form.categories %}
    {# json_decode() part is imaginary #}
    {% set obj = category.vars.label|json_decode() %}
{% endfor %}

最佳答案

这很容易,如果你extend twig .

首先,创建一个包含扩展的类:

<?php
 
namespace Acme\DemoBundle\Twig\Extension;

use Symfony\Component\DependencyInjection\ContainerInterface;  
use \Twig_Extension;

class VarsExtension extends Twig_Extension
{
    protected $container;
 
    public function __construct(ContainerInterface $container) 
    {
        $this->container = $container;
    }
      
    public function getName() 
    {
        return 'some.extension';
    }
    
    public function getFilters() {
        return array(
            'json_decode'   => new \Twig_Filter_Method($this, 'jsonDecode'),
        );
    }

    public function jsonDecode($str) {
        return json_decode($str);
    }
}

然后,在您的 Services.xml 文件中注册该类:

<service id="some_id" class="Acme\DemoBundle\Twig\Extension\VarsExtension">
        <tag name="twig.extension" />
        <argument type="service" id="service_container" />
</service>

然后,在你的 Twig 模板上使用它:

{% set obj = form_label(category) | json_decode %}

关于php - 在 Twig 中解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14500698/

相关文章:

php - 如何在 Symfony2 表单生成器中添加 <hr> ?

symfony - Twig 宏 VS 包括?

php - 如何通过 php 添加 @ 符号作为 JSON 中对象名称的一部分

php - 适合新手的友好 PHP 框架?

Symfony IP 访问控制配置不起作用

php - Symfony2 - SonataAdmin - 空 admin_list block

mongodb - 如何在 symfony2 twig 模板中显示 mongodb 日期?

php - 用要初始化的值填充关联数组

php - 将今天的日期与数据库中列出的日期进行比较

Symfony 2.3 getRequest()-> headers 不显示授权承载 token