Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在Twig中解码JSON_Php_Symfony_Twig - Fatal编程技术网

Php 在Twig中解码JSON

Php 在Twig中解码JSON,php,symfony,twig,Php,Symfony,Twig,可以在twig中解码JSON吗?谷歌似乎对此毫无收获。在Twig中解码JSON没有意义吗 我试图访问Symfony2的实体字段类型()上的2个实体属性 在遇到前面的两个SO问题(和)后,我想到(并且做了)返回一个表示对象实例的JSON字符串,这两个问题建议向实体添加一个额外的方法来检索自定义字符串,而不是实体属性 实体类中的某个位置: /** * Return a JSON string representing this class. */ public function getJson

可以在twig中解码JSON吗?谷歌似乎对此毫无收获。在Twig中解码JSON没有意义吗


我试图访问Symfony2的实体字段类型()上的2个实体属性

在遇到前面的两个SO问题(和)后,我想到(并且做了)返回一个表示对象实例的JSON字符串,这两个问题建议向实体添加一个额外的方法来检索自定义字符串,而不是实体属性

实体类中的某个位置:

/**
 * Return a JSON string representing this class.
 */
public function getJson()
{
   return json_encode(get_object_vars($this));
}
在形式上(类似于):

后来,我希望在Twig中对它进行解码

{% for category in form.categories %}
    {# json_decode() part is imaginary #}
    {% set obj = category.vars.label|json_decode() %}
{% endfor %}
如果你愿意,那很容易

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

<?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);
    }
}
然后,在细枝模板上使用它:

{% set obj = form_label(category) | json_decode %}

我想出了一种获取JSON的方法,我想我会在这里分享它,以防它对其他人有用

所以在我的例子中,我可能有10条从mysql数据库返回的记录(布局),每行都有一个名为properties的字段,它是一个json字符串。因此,我可以轻松地取出记录并将其发送到模板,如下所示:

echo $twig->render('template.html.twig', array(
      "layouts" => $layouts,
));
不过,到目前为止还不错,当我在twig中执行{layouts in layouts%}中的{%for layout时,无法访问属性字段项,因为它们仍然是json字符串

因此,就在我将$layouts传递给细枝模板之前,我做了以下工作:

foreach($layouts as $i => $v)
{
      $layouts[$i]->decoded = json_decode($v->getProperties());
}
通过这样做,我在我的对象中动态创建了一个名为“decoded”的变量,其中包含json解码对象

现在在我的模板中,我可以通过{{layout.decoded.whatever}访问json项


这可能有点老套,不是每个人都能想到一个好的解决方案。对于我来说,我工作得很好,开销很小,这意味着我不必在树枝到达模板之前就开始扩展树枝了。

这是上述所有工作的一种选择。
我不知道这是否是最佳的解决方案,但它能起作用

1) 创建一个助手函数并注册该函数。

<?php
function twig_json_decode($json)
{
    return json_decode($json, true);
}

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'),
        ];
    }
}

在我的例子中,我的实体中有一个JsonArray,然后我在实体中添加了一个methode

<?php
namespace ACME\DefaultBundle\Entity;
/*...*/    
public function getDecodedPath()
{
    return json_decode($this->path);
}

这是一个老问题,但我正在添加我的解决方案以供记录。。。只需使用SimpleFunction扩展细枝:

// 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);
用法:

在调用细枝渲染之前,将_json_变量设置为字符串“[“1”、“2”、“3”、“4”、“5”]”

细枝模板:

The values are: {{ json_to_list(a_json_variable) }}
将产生

The values are: 1, 2, 3, 4, 5

为什么不在PHP中使用
json\u encode()
it?是的,我使用
json\u encode(get\u object\u vars($this))
。问题是解码,因为它必须在Twig中,而不是PHP中。我不熟悉Twig/Symfony2,但您能在您的操作中解码它并将结果传递给您的Twig模板吗?您好@halfer,您无法访问控制器中的实体(Sf1中的模型对象)。表单(使用
$builder
构建)自行查询类别,我所能做的就是配置将用于在要呈现的实际表单中标记它的属性。您知道可以扩展细枝并编写自定义过滤器吗?以防万一有人在寻找Services.yml设置:
acme\u demo.twig.extension.vars\u extension:class:acme\DemoBundle\twig\extension\VarsExtension参数:[@service\u container]标记:-{name:'twig.extension'}
如果您只是在没有框架的情况下使用twig,会发生什么:(@Xocoatzin,我看了你的答案,这与我正在寻找的相关。但我也有一个问题。我以前做过一个TWIG扩展类,并在构造函数中使用:`public function\uu construct(\TWIG\u Environment$env){$this->Environment=$env;}`,我确实使用了
$this->environment
以后在其上使用函数
loadTemplate(“…”)
。在您的解决方案中,我对使用
ContainerInterface
感到有点困惑,我不明白需要参数
[@service\u container]
的地方(如果你不知道自己是否需要它,那么你就不需要了)您可以安全地删除它。从
Services.xml
中删除
行、
\uu构造的参数和主体、行
受保护的$container;
使用…containerInterface
遵循类似方法的更好解决方案是创建一个接收解码JSON的视图模型/DTO
// 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);
The values are: {{ json_to_list(a_json_variable) }}
The values are: 1, 2, 3, 4, 5