简体   繁体   中英

Twig concatenation on variables

I'm using twig.

I am trying to fetch values from my answer array in a dynamic way.

{% set value = question.slug %} // eg "satisfied_with_response"
{{ answer.satisfied_with_response }} // eg "4"

So I am trying to concatenate the response object;

{{ answer.value }} // doesn't work

How should I do this?

{{ answer[value] }} should work - but only if answer is an array.

Citing the documentation :

For convenience's sake foo.bar does the following things on the PHP layer:

  • check if foo is an array and bar a valid element;
  • if not, and if foo is an object, check that bar is a valid property;
  • if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead);
  • if not, and if foo is an object, check that getBar is a valid method;
  • if not, and if foo is an object, check that isBar is a valid method;
  • if not, return a null value.

foo['bar'] on the other hand only works with PHP arrays:

  • check if foo is an array and bar a valid element;
  • if not, return a null value.

If you need to have the same features foo.bar provides you could use {{ attribute(answer, value) }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM