php – 在Twig中解码JSON

有可能在树枝上解码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>

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

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...