jmack
jmack

Reputation: 189

Cycle through and pull information from array in Twig

I currently have an array full of pre-populated form fields:

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

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

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

My objective is to cycle through the fields array and see if I have any information in my $info array to pre-populate the field with.

Something like:

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

But obviously in Twig, currently I 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.

Upvotes: 3

Views: 60

Answers (1)

Matteo
Matteo

Reputation: 39470

this example dump 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 the working solutions: http://twigfiddle.com/i3w2j3

Hope this help

Upvotes: 1

Related Questions