php 在 Twig 中解码 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14500698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Decoding JSON in Twig
提问by Czar Pino
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?
是否可以在树枝中解码 JSON?谷歌搜索似乎对此没有任何结果。在 Twig 中解码 JSON 没有意义吗?
I'm trying to access 2 entity properties on an Symfony2's entity field type (Entity Field Type).
我正在尝试访问 Symfony2 的实体字段类型(实体字段类型)上的 2 个实体属性。
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.
在遇到之前的 2 个 SO 问题(Symfony2 entity field type替代“property”或“__toString()”?和Symfony 2 Create a entity form field with 2 properties)后,建议向实体添加一个额外的方法来检索自定义字符串我想到(并且确实)返回一个表示对象实例的 JSON 字符串,而不是实体属性。
Somewhere in the entity class:
在实体类中的某处:
/**
* 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',
...
));
Afterwards, I was hoping to json_decodeit in Twig...
之后,我希望能json_decode在 Twig 中实现...
{% for category in form.categories %}
{# json_decode() part is imaginary #}
{% set obj = category.vars.label|json_decode() %}
{% endfor %}
回答by Xocoatzin
Thats easy if you extend twig.
如果你扩展 twig ,那很容易。
First, create a class that will contain the extension:
首先,创建一个包含扩展的类:
<?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);
}
}
Then, register that class in your Services.xml file:
然后,在您的 Services.xml 文件中注册该类:
<service id="some_id" class="Acme\DemoBundle\Twig\Extension\VarsExtension">
<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 %}
回答by Parag Tyagi -morpheus-
An alternativeto all above.
And I don't know whether this is the optimal solution, but it works.
以上所有的替代方案。
我不知道这是否是最佳解决方案,但它有效。
1) Create a helper functionand registerthat function it.
1) 创建一个辅助函数并注册该函数。
<?php
function twig_json_decode($json)
{
return json_decode($json, true);
}
2) Use this function in your twig file.
2)在你的树枝文件中使用这个功能。
{% set res = twig_json_decode(json) %}
# above will return an array which can be iterated
{% for r is res %}
{{ r }}
{% endfor %}
回答by azzy81
I came up with a way of getting to my JSON and I thought I'd share it here in case its usefult to someone else.
我想出了一种获取我的 JSON 的方法,我想我会在这里分享它,以防它对其他人有用。
so in my case I have maybe 10 records (layouts) returned from a mysql db and each row has a field called properties which is a json string. So, I can easily pull out the records and send them to the template like so:
所以在我的情况下,我可能有 10 条记录(布局)从 mysql db 返回,每一行都有一个名为 properties 的字段,它是一个 json 字符串。因此,我可以轻松地提取记录并将它们发送到模板,如下所示:
echo $twig->render('template.html.twig', array(
"layouts" => $layouts,
));
So far so good, However when I do my {% for layout in layouts %} in twig there is no way to get to the properties field items as they are still a json string.
到目前为止一切顺利,但是当我在 twig 中执行 {% for layout in layouts %} 时,无法访问属性字段项,因为它们仍然是 json 字符串。
So just before I passed $layouts to the twig template I did the following:
因此,就在我将 $layouts 传递给 twig 模板之前,我执行了以下操作:
foreach($layouts as $i => $v)
{
$layouts[$i]->decoded = json_decode($v->getProperties());
}
by doing this Ive created a variable on the fly within my object called 'decoded' which contains the json decoded object.
通过这样做,我在我的对象中动态创建了一个名为“解码”的变量,其中包含 json 解码对象。
So now in my template I can access my json items by {{ layout.decoded.whatever }}
所以现在在我的模板中,我可以通过 {{ layout.decoded.whatever }} 访问我的 json 项目
This might be a bit hacky and not to everyones idea of a good solution. I works well for me, very little overhead and means I dont have to mess about with extending twig as Im doing the work before it gets to the template.
这可能有点 hacky,而不是每个人对一个好的解决方案的想法。我对我来说工作得很好,开销很小,这意味着我不必在扩展树枝时搞砸,因为我在它到达模板之前正在做这项工作。
回答by Chris Hasiński
Updated code for Symfony2.8 or Symfony3:
Symfony2.8 或 Symfony3 的更新代码:
<?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';
}
// Note: If you want to use it as {{ json_decode(var) }} instead of
// {{ var|json_decode }} please use getFunctions() and
// new \Twig_SimpleFunction('json_decode', 'json_decode')
public function getFilters() {
return [
// Note that we map php json_decode function to
// extension filter of the same name
new \Twig_SimpleFilter('json_decode', 'json_decode'),
];
}
}
回答by S.Alfano
In my case i have got an JsonArray in my Entity then i've add in my Entity a methode
就我而言,我的实体中有一个 JsonArray,然后我在实体中添加了一个方法
<?php
namespace ACME\DefaultBundle\Entity;
/*...*/
public function getDecodedPath()
{
return json_decode($this->path);
}
回答by Ryan Griggs
This is an old question but I'm adding my solution for the record... Just extend Twig with a SimpleFunction:
这是一个老问题,但我正在添加我的记录解决方案......只需使用 SimpleFunction 扩展 Twig:
// Return a string of separated values from a JSON string
// Can optionally specify a separator. If none provided, ", " is used.
$function = new Twig_SimpleFunction('json_to_list', function($json, $separator = ", ")
{
$result = "";
$array = json_decode($json, true);
foreach ($array as $item)
{
if ($result != "") { $result .= $separator; }
$result .= $item;
}
return $result;
});
$twig->addFunction($function);
Usage:
用法:
set a_json_variable to the string '["1","2","3","4","5"]' before calling the Twig render.
在调用 Twig 渲染之前,将 a_json_variable 设置为字符串 '["1","2","3","4","5"]'。
Twig template:
树枝模板:
The values are: {{ json_to_list(a_json_variable) }}
Will produce
会产生
The values are: 1, 2, 3, 4, 5

