mikelovelyuk
mikelovelyuk

Reputation: 4152

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?

Upvotes: 1

Views: 82

Answers (1)

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

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

Upvotes: 3

Related Questions