php 使用 Twig 生成 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21396530/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:06:45  来源:igfitidea点击:

Using Twig to generate JSON

phpjqueryjsontwig

提问by russellmania

I want to have a URL that returns a simple JSON object. I am trying to use Twig to generate the JSON object:

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

{
"urls": [
{% for child in page.root %}
    "{{ child.url }}"{% if not loop.last %},{% endif %}
{% endfor %}
]
}

The carriage returns will not remain in place though, and I keep getting a result that looks like this:

但是回车不会保留在原位,我不断得到如下所示的结果:

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

which Jquery will not parse with it's ajax or getJSON methods. It's totally ignoring this JSON. How might I convince Twig to put the right whitespace in place? I've looked at the manual and it only seems concerned with NOT inserting whitespace.

Jquery 不会用它的 ajax 或 getJSON 方法解析。它完全忽略了这个 JSON。我如何说服 Twig 放置正确的空格?我看过手册,似乎只关心不插入空格。

回答by biera

That works for me (twig template):

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

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

And that:

然后:

console.log(parsedJSON);

will output:

将输出:

 Array ["one", "two", "three"]

in FF console.

在 FF 控制台中。

回答by DasBaconfist

Twig has a filter for this.

Twig 有一个过滤器。

json_encode, it uses PHP json_encode function.

json_encode,它使用 PHP json_encode 函数。

for your case:

对于您的情况:

{{ {'urls': page.root}|json_encode }}

will output

会输出

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

the code is tested and works. For more information take a look at the Twig Documentation for json_encode.

代码经过测试并有效。有关更多信息,请查看json_encode的 Twig 文档。

回答by Alain Tiemblo

Don't use Twig to generate your json response.

不要使用 Twig 来生成你的 json 响应。

In your controller, use:

在您的控制器中,使用:

return new Response(json_encode($var));

Sample:

样本:

public function sampleAction()
{
    $urls = array('../test', '../something', '../sample');
    return new Response(json_encode($var));
}

If URLs are generated from Symfony2 routes, you can use:

如果 URL 是从 Symfony2 路由生成的,您可以使用:

public function sampleAction()
{
    $urls = array(
             $this->generateUrl('my_test'),
             $this->generateUrl('my_something'),
             $this->generateUrl('my_sample'),
    );
    return new Response(json_encode($var));
}

回答by Ravi Chauhan

Thats easy if you extend 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);
    }
}

回答by vivek

Basically the $.getJson()method requires json but ther is a string so you can use $.get()to get the response and use the parser to parse the string to JSON

基本上$.getJson()方法需要 json 但有一个字符串,因此您可以使用$.get()获取响应并使用解析器将字符串解析为 JSON

 $.get("ffff",function(data){
 // user parser
 JSON.parse();
 });