Ron Piggott
Ron Piggott

Reputation: 705

represent a variable in twig using for loop

In my Service I return an array which looks like this:

$array = [
    'bible_anagram_word'    => $result->getBibleAnagramWord(),
    'word_1'                => $result->getWord1(),
    'word_2'                => $result->getWord2(),
    'word_3'                => $result->getWord3(),
    ...
    'word_22'               => $result->getWord22(),
    'word_23'               => $result->getWord23(),
    'word_24'               => $result->getWord24(),
    'word_25'               => $result->getWord25(),
    'Bible_verse_reference' => $result->getBibleVerseReference(),
    'Bible_verse_text'      => $result->getBibleVerseText(),
    'Bible_translation'     => $result->getBibleTranslation(),
];

How do I represent document.word_## in this for loop?

{% for i in 1..25 %}
    {{ document.word_ ~ i|slice(0,1) }}
{% endfor %}

In PHP this code is:

substr ( $this->document['word_'.$i] , 0 , 1 )

My unsuccessful attempts include:

Upvotes: 3

Views: 1042

Answers (1)

Richard
Richard

Reputation: 4129

This should do the trick

{{ attribute(document, 'word_' ~ i) }} 

More on attribute function

Upvotes: 6

Related Questions