3

I have a specific problem with concat of twig. When I trying to concatenate dynamic variables showing the error. Here is my code :

{% set i = 0 %}
{% set nbLignes = codeEvt.nb_lignes_~i %}
{% set nbLignesRef = codeEvt.nb_lignes_ref_~i %}

But I have this error message :

Method "nb_lignes_" for object "\DTO\SuiviJourFonc" does not exist in XXXXXXXXX.html.twig at line 211

I would like to take codeEvt.nb_lignes_0 , but i would like build a "for" for others variables like nb_lignes_1, nb_lignes_2 , nb_lignes_3 ...

How can i do this ?

Marek
  • 7,337
  • 1
  • 22
  • 33
alexandre bru
  • 103
  • 2
  • 9

2 Answers2

6

attribute can be used to access a dynamic attribute of a variable: The attribute function was added in Twig 1.2.

{{ attribute(object, method) }}

{{ attribute(object, method,arguments) }}

{{ attribute(array, item) }}

Try like this,

{{ attribute(codeEvt, 'nb_lignes_ref_' ~ i) }}
Nisam
  • 2,275
  • 21
  • 32
0

You can try the array-like notation:

{{ codeEvt['nb_lignes_ref_' ~ i] }}

Or even use string interpolation:

{{ codeEvt["nb_lignes_ref_#{i}"] }}
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153