Twig 中可见的 Symfony 原则

Symfony Doctrine Visible in Twig

我有字段类型

 /**
 * @var array
 *
 * @ORM\Column(name="raw", type="json_array", nullable=true)
 */
private $raw;

我设置了这个归档数据格式json

 $jsonRaw = array(
                    'repository_language' => $repository['language'],
                    'used_languages' => $languages,
                    'commits' => $commits,
                    'scooped_branch' => $sha,
                    'first_commit' => empty($this->committer[0]['author']) ? null : $this->committer[0],
                    'last_commit' => empty($this->committer[1]['author']) ? null : $this->committer[1]
                );

并在实体中设置

$entity->setRaw(json_encode($jsonRaw));

然后我在这个字段中有数据 field_data 我在模板中渲染这个字段但是有错误

                {% for languages in project.raw.used_languages|json_decode %}
                    <div class="row col-sm-2" style="position: relative; text-align: center; margin: 0; padding: 0;">
                        <small style="color: #00312f;">
                            <strong>{{ languages.lang }}</strong>:<br>
                            {{ languages.percent|round(1, 'floor') }}%<br>
                        </small>
                    </div>
                {% endfor %}

Impossible to access an attribute ("used_languages") on a string variable ("{"repository_language":"PHP","used_languages":[{"lang":"PHP","percent.....

为什么??我这可能不是 json 的 twig 朋友并创建自定义 twig 过滤器

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);
}
}

并尝试使用

               {% for languages in project.raw.used_languages|json_decode %}
                    <div class="row col-sm-2" style="position: relative; text-align: center; margin: 0; padding: 0;">
                        <small style="color: #00312f;">
                            <strong>{{ languages.lang }}</strong>:<br>
                            {{ languages.percent|round(1, 'floor') }}%<br>
                        </small>
                    </div>
                {% endfor %}

仍然有错误

Impossible to access an attribute ("used_languages") on a string variable ("{"repository_language":"PHP","used_languages":[{"lang":"PHP","percent":75.976812123425},{"lang":"JavaScript","percent":13.194136518949},{"lang":"CSS","percent":10.829051357625}],

请帮忙,我不知道(

您可以在按键访问元素之前简单地应用过滤器 json_decode,如@Snoozer 示例:

{% set raw = project.raw | json_decode %} {{ raw.used_languages }}