gpt4 book ai didi

php - 在 Twig 中解码 JSON

转载 作者:IT王子 更新时间:2023-10-29 01:21:43 25 4
gpt4 key购买 nike

是否可以在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com