有可能在树枝上解码JSON吗?谷歌搜索似乎没有任何关于这一点.在Twig中解码JSON没有意义吗?
我正在尝试访问Symfony2的实体字段类型(实体字段类型)上的2个实体属性.
在遇到2个先前的SO问题(Symfony2实体字段类型替代"property"或"__toString()"?和Symfony 2创建具有2个属性的实体表单字段)后,建议向实体添加额外方法以检索自定义字符串我想到(并且确实)返回表示对象实例的JSON字符串而不是实体属性.
实体类中的某个地方:
/**
* Return a JSON string representing this class.
*/
public function getJson()
{
return json_encode(get_object_vars($this));
}
Run Code Online (Sandbox Code Playgroud)
并在形式(类似):
$builder->add('categories', 'entity', array (
...
'property' => 'json',
...
));
Run Code Online (Sandbox Code Playgroud)
之后,我希望json_decode在Twig中...
{% for category in form.categories %}
{# json_decode() part is imaginary #}
{% set obj = category.vars.label|json_decode() %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
Xoc*_*zin 37
如果你延长枝条,这很容易.
首先,创建一个包含扩展名的类:
<?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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在Services.xml文件中注册该类:
<service id="some_id" class="Acme\DemoBundle\Twig\Extension\VarsExtension">
<tag name="twig.extension" />
<argument type="service" id="service_container" />
</service>
Run Code Online (Sandbox Code Playgroud)
然后,在您的树枝模板上使用它:
{% set obj = form_label(category) | json_decode %}
Run Code Online (Sandbox Code Playgroud)
以上所有的替代方案.
我不知道这是否是最佳解决方案,但它确实有效.
1)创建一个辅助函数并注册它的功能.
<?php
function twig_json_decode($json)
{
return json_decode($json, true);
}
Run Code Online (Sandbox Code Playgroud)
2)在twig文件中使用此功能.
{% set res = twig_json_decode(json) %}
# above will return an array which can be iterated
{% for r is res %}
{{ r }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我想出了一种获取JSON的方法,我想在这里共享它,以防它对其他人有用。
所以在我的情况下,我可能从mysql数据库返回了10条记录(布局),每一行都有一个名为properties的字段,它是一个json字符串。因此,我可以轻松地提取记录并将其发送到模板,如下所示:
echo $twig->render('template.html.twig', array(
"layouts" => $layouts,
));
Run Code Online (Sandbox Code Playgroud)
到目前为止,还不错,但是当我在细枝中执行{%for layouts in layouts%}时,由于属性字段项仍然是json字符串,因此无法访问它们。
因此,在将$ layouts传递到树枝模板之前,我做了以下工作:
foreach($layouts as $i => $v)
{
$layouts[$i]->decoded = json_decode($v->getProperties());
}
Run Code Online (Sandbox Code Playgroud)
通过这样做,我在我的对象“ decoded”中动态创建了一个变量,其中包含json解码的对象。
因此,现在在我的模板中,我可以通过{{layout.decoded.whatever}}访问我的json项
这可能有点棘手,但并不是每个人都认为一个好的解决方案。我为我工作得很好,只有很少的开销,这意味着我不必在我进入模板之前就进行细枝延伸。