在 Twig 中解码 JSON [英] Decoding JSON in Twig

查看:39
本文介绍了在 Twig 中解码 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is is possible to decode JSON in twig? Googling doesn't seem to yield anything about this. Does decoding JSON in Twig not make sense?

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

I'm trying to access 2 entity properties on an Symfony2's entity field type (Entity Field Type).

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

After coming across 2 previous SO questions ( Symfony2 entity field type alternatives to "property" or "__toString()"? and Symfony 2 Create a entity form field with 2 properties ) which suggested adding an extra method to an entity to retrieve a customized string rather than an entity attribute, I thought of (and did) returning a JSON string representing an object instance.

实体类中的某处:

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

并且在形式(类似)中:

And in the form (something like):

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

之后,我希望在 Twig 中 json_decode ......

Afterwards, I was hoping to json_decode it in Twig...

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

推荐答案

如果你延长树枝.

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

First, create a class that will contain the extension:

<?php
 
namespace AcmeDemoBundleTwigExtension;

use SymfonyComponentDependencyInjectionContainerInterface;  
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 文件中注册该类:

Then, register that class in your Services.xml file:

<service id="some_id" class="AcmeDemoBundleTwigExtensionVarsExtension">
        <tag name="twig.extension" />
        <argument type="service" id="service_container" />
</service>

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

Then, use it on your twig templates:

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

这篇关于在 Twig 中解码 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆