将另一个数组中的值替换为数组twig

时间:2017-04-26 23:10:04

标签: php silex

如何在一个循环中将一个值从一个数组插入另一个数组? 例如

{% for day_item in template_string %}
    <div id="{{lessons.{{day_item.template_string}}.id}}" class="col-lg-2 no-padding col-md-2 col-sm-12 col-xs-12"></div>
{% endfor %}

2 个答案:

答案 0 :(得分:1)

这是一个演示:

php代码:

// data for twig template
$data = [
    'userIds' => [1, 2, 3],
    'users'   => [
        1 => 'Tony',
        2 => 'Allen',
        3 => 'Peter',
    ],
];

twig code:

{% for userId in userIds %}
    <li>{{ users[userId] }}</li>
{% endfor %}

只需在Twig中使用[ ]来访问带有twig变量的数组值。

并且渲染的html是

<li>Tony</li>
<li>Allen</li>
<li>Peter</li>

答案 1 :(得分:0)

我遇到了同样的问题,并且发现Tony的解决方案很好,但是试图用文字直接内联:

<form class="form-inline" action="./action.php?" method="GET">
<div class="form-group">
    <label for="query_term">Term:</label> 
    <select class="form-control" name="" id="query_term">
        <option value="">Select</option>
        {% set term_labels = { SP: 'Spring', SU: 'Summer', FA: 'Fall' } %}
        {% for term_value in ["SP", "SU", "FA"] %}
            {% if term_value == cur_term  %} {#TODO: provide cur_term#}
                <option value="{{ term_value }}" selected='selected'>{{ term_labels[term_value] }}</option>
            {% else %}
                <option value="{{ term_value }}">{{ term_labels[term_value] }}</option>
            {% endif %}
        {% endfor %}
    </select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

注意:这是一个3步引导程序,具有通过树枝模板创建的动态选择下拉菜单。

相关问题