使用Twig生成JSON

rus*_*nia 7 php jquery json twig

我想要一个返回简单JSON对象的URL.我正在尝试使用Twig生成JSON对象:

{
"urls": [
{% for child in page.root %}
    "{{ child.url }}"{% if not loop.last %},{% endif %}
{% endfor %}
]
}
Run Code Online (Sandbox Code Playgroud)

回车不会留在原地,我会得到一个如下所示的结果:

{'urls':['../ants/','../brick-report/','../the-pollution-intervention/','../barclay/','../broken-advertising/','../aldat-n-densom/','../thisisart/','../there-she-goes-again/']}
Run Code Online (Sandbox Code Playgroud)

哪个Jquery不会用它的ajax或getJSON方法解析.它完全忽略了这个JSON.我怎么能说服Twig把正确的空白放到位呢?我查看了手册,它似乎只关心不插入空格.

bie*_*era 13

这对我有用(树枝模板):

var parsedJSON = JSON.parse('{{ ['one', 'two', 'three']|json_encode|e('js') }}');
Run Code Online (Sandbox Code Playgroud)

然后:

console.log(parsedJSON);
Run Code Online (Sandbox Code Playgroud)

将输出:

 Array ["one", "two", "three"]
Run Code Online (Sandbox Code Playgroud)

在FF控制台.


小智 5

Twig为此提供了一个过滤器。

json_encode,它使用PHP json_encode函数。

对于您的情况:

{{ {'urls': page.root}|json_encode }}
Run Code Online (Sandbox Code Playgroud)

将输出

{"urls":["..\/ants\/","..\/brick-report\/","..\/the-pollution-intervention\/","..\/barclay\/","..\/broken-advertising\/","..\/aldat-n-densom\/","..\/thisisart\/","..\/there-she-goes-again\/"]}
Run Code Online (Sandbox Code Playgroud)

该代码已经过测试并且可以正常工作。有关更多信息,请参阅Twig文档中的json_encode


小智 -1

如果你延长树枝,那就很容易了。

首先,创建一个包含扩展的类:

<?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)