If you're passing variables from your controller to more than one identical twig templates then you can use include ... with {...} function in a base template instead. In such case, you create a base template that contains the content and two other templates which include base template by passing variables to it.


Controller


For example, array below is passed to MyApiBundle:Message:tem_1.txt.twig and MyApiBundle:Message:tem_2.txt.twig.


$templateVariables = [
'var1' => 'Hello',
'var2' => 'World',
];

Template structure


tem_1_2_base.txt.twig


# my-project/src/My/ApiBundle/Resources/views/Message/tem_1_2_base.txt.twig

Hi,

I say {{ var1 }} then {{ var2 }}

Bye

tem_1.txt.twig


# my-project/src/My/ApiBundle/Resources/views/Message/tem_1.txt.twig

{% include 'MyApiBundle:Message:tem_1_2_base.txt.twig'
with {
'var1': var1,
'var2': var2
} %}

tem_2.txt.twig


# my-project/src/My/ApiBundle/Resources/views/Message/tem_2.txt.twig

{% include 'MyApiBundle:Message:tem_1_2_base.txt.twig'
with {
'var1': var1,
'var2': var2
} %}