Looping and extracting information from an array in Twig

Currently I have an array with filled fields of filled fields:

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

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

      

As you can see, this particular array of fields only contains the title and name.

My goal is to loop through an array of fields and see if I have any information in my array $info

to pre-populate the field.

Something like:

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

      

But obviously in Twig, I currently have something like:

{% 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 %}

      

Any help is greatly appreciated.

+3


source to share


1 answer


this example dumps what you need:

{%  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 %}

      

Result:



Mr john

Here's working solutions: http://twigfiddle.com/i3w2j3

Hope for this help

+1


source







All Articles