Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • http://twig.sensiolabs.org/doc/tags/include.html
  • http://twig.sensiolabs.org/doc/functions/include.html
like image 625
JohnnyC Avatar asked Jun 12 '14 09:06

JohnnyC


2 Answers

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.
like image 141
Alain Tiemblo Avatar answered Oct 14 '22 22:10

Alain Tiemblo


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)
like image 20
karolhor Avatar answered Oct 14 '22 20:10

karolhor