在 Twig 中循环并从数组中提取信息

Cycle through and pull information from array in Twig

我目前有一个包含 pre-populated 个表单字段的数组:

$fields = array('title','first_name')

$info = array(
    'title' => 'Mr',
    'first_name' => 'John',
    'last_name' => 'Smith'
)

如您所见,这个特定的字段数组仅包含标题和名字。

我的objective是循环遍历fields数组,看看我的$info数组里有没有信息到pre-populate那个字段。

类似于:

foreach (fields as field) {
    if (field  is in $info array) {
        echo the_field_value;
    }
}

但显然在 Twig 中,目前我有类似的东西:

{% for key, field in context.contenttype.fields %}
    {% if key in context.content|keys %} << is array
        {{ key.value }}<< get the value of the field
    {%  endif %}
{% endfor %}

非常感谢任何帮助。

此示例转储您需要的内容:

{%  set fields = ['title','first_name'] %}

{% set info = { 'title': 'Mr', 'first_name': 'John', 'last_name': 'Smith' } %}


{% for key in fields %}
    {% if key in info|keys %}
        {{ info[key] }}
    {%  endif %}
{% endfor %}

结果:

Mr John

这里是可行的解决方案:http://twigfiddle.com/i3w2j3

希望对您有所帮助