有可能在树枝上解码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);
}
}
<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 %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。