php - 选择元素到 foreach Twig 模板中

标签 php symfony twig

我在 Symfony2 上使用 Twig,参数中有 2 个数组:

我的 Controller :

return $this->render('MyBundle:Default:index.html.twig',
                             array('checked' => $boxChecked,
                                   'choices' => $choices));

变量“checked”和“choices”是两个数组,我想显示 $checked[$choices[$i]] 的值以与 true 或 false 进行比较,以将检查或不应用到 twig tpl 的输入中。

这是我的代码,但不起作用:

{% for choice in choices %}

      {% if checked.{{choice}} == true %}

        <div class="choice">{{ choice|capitalize }} <input type="checkbox" id="{{ choice }}" /></div>

    {% else %}

        <div class="choice">{{ choice|capitalize }} <input type="checkbox" id="{{ choice }}" checked="checked" /> </div>

    {% endif %}

{% endfor %}

错误是:“MyBundle:Default:index.html.twig”中的预期名称或编号第 22 行(500 内部服务器错误)

第 22 行是:{% if selected.{{choice}} == true %}

我不知道如何检查我的。(我的VAR选择进入我的foreach选择)到twig tpl?

最佳答案

您必须使用括号语法:

    {% for choice in choices %}

          {% if checked[choice] == true %}

            <div class="choice">{{ choice|capitalize }} <input type="checkbox" id="{{ choice }}" /></div>

        {% else %}

            <div class="choice">{{ choice|capitalize }} <input type="checkbox" id="{{ choice }}" checked="checked" /> </div>

        {% endif %}

    {% endfor %}

关于php - 选择元素到 foreach Twig 模板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17041208/

相关文章:

php - 如何在一个查询中更新两个表?

php - .htaccess 将 css 重定向到 php

php - 检查关联是否存在而不捕获 Doctrine2 中的异常?

symfony - 从 Twig 按需调用 Symfony 服务

php - 你会如何在 Twig 中的 {%%} 内执行三元条件

php - PHP判断字符串中特殊字符的位置

php - Symfony 3,DI - 将服务添加到参数

Symfony2 和 Doctrine2 : Create custom annotations

php - 如何获取/打印对我的 Twig 模板 (Drupal 8) 的实体引用的路径或 url?

PHP - 比较日期,检查是否在最后一小时内