JohnnyC
JohnnyC

Reputation: 1435

Difference between {% include '' %} and {{ include('') }} in Twig

It's possible to include a file in two different ways:

{% include 'fic.html.twig' %} 
{{ include('fic.html.twig') }} 

What is the difference between the two methods?

Source:

Upvotes: 11

Views: 2818

Answers (4)

Alain
Alain

Reputation: 36954

Tags are less flexible than functions, for example:

  1. If you want to store contents of a file in a variable if you want to repeat it twice:

    {% set content = include('test.twig') %}

Instead of:

{% set content %}
{% include 'test.twig' %}
{% endset %}
  1. If you want to add filters:

    {{ include('alert.twig') | upper }}

Its tag equivalent:

{% set temp %}
{% include 'alert.twig' %}
{% endset %}
{{ temp | upper }}

You see, {{ include }} instead of {% include %} will not change the world, but remove some complexity when you need to do tricky stuffs using Twig.

Also, according to the documentation, it is recommended to use {{ include() }} to fit with best practices:

{{ }} is used to print the result of an expression evaluation;
{% %} is used to execute statements.

Upvotes: 14

medunes
medunes

Reputation: 586

From Symfony 2.8 (LTS) documentation

2.3 The include() function is available since Symfony 2.3. Prior, the {% include %} tag was used.

Upvotes: 0

karolhor
karolhor

Reputation: 302

From Twig's changelog:

* 1.12.0-RC1 (2012-12-29)

 * added an include function (does the same as the include tag but in a more flexible way)

Upvotes: 3

vobence
vobence

Reputation: 523

I think it's the same functionality, but while {% include '' %} is a tag, the {{ include('') }} is a function. Maybe if you want to overwrite the function it can be easier than a tag.

Upvotes: 1

Related Questions