选择元素到foreach Twig模板

kee*_*zer 2 php symfony twig

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

我的控制器:

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

Vars'已检查'和'选择'是两个数组,我想显示$ checked [$ choices [$ i]]的值来与true ofr进行比较以将已检查或未应用于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 %}
Run Code Online (Sandbox Code Playgroud)

错误是: Expected name or number in &quot;MyBundle:Default:index.html.twig&quot; at line 22 (500 Internal Server Error)

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

我不知道我的检查结果如何(我的选择进入我的预期选择)到twig tpl?

Mic*_*bov 5

您必须使用括号语法:

    {% 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 %}
Run Code Online (Sandbox Code Playgroud)