Twig is a template engine for the PHP programming language. Its syntax originates from Jinja and Django templates. It's an open source product licensed under a BSD License and maintained by Fabien Potencier. The initial version was created by Armin Ronacher. Symfony PHP framework comes with a bundled support for Twig as its default template engine since version 2.
When it comes to template engines in PHP, many people will tell you that PHP itself is a template engine. But even if PHP started its life as a template language, it did not evolve like one in the recent years. As a matter of fact, it doesn't support many features modern template engines should have nowadays.
print render($content);
{{ content }}
Twig--> compile (symphony)--> PHP code: Symphony compiles twig syntax to php code
{{ ... }}
, to print the content of variables or the result of evaluating an expression (e.g.: an inherited Twig template with {{ parent() }}
). print/echo something {# ... #}
, to add comments in the templates. These comments aren't included in the rendered page.{% ... %}
,to execute statements, such as for-loops. do something. (set var, condition).
{% if label %}
{{ label }}
{% endif %}
“The most powerful part of Twig is template inheritance” – Sensiolabs
{% include "@molecules/slidercard/upcomingevent.twig" with { ... } %}
{% embed ''@molecules/slidercard/upcomingevent.twig'' %}
{% extends "themes/sub_bartik/templates/node.html.twig" %}
The operators precedence is, from the less to more priority:
Operator | Role |
---|---|
b-and | Bitwise AND |
b-xor | Bitwise XOR |
b-or | Bitwise OR |
or | Or |
and | And |
== | Is equal? |
!= | Is different? |
< | Inferior |
> | Superior |
>= | Superior or equal |
<= | Inferior or equal |
in | into |
matches | Corresponds |
starts with | Begins by |
ends with | Finishes by |
.. | Sequence (ex: 1..5) |
+ | Plus |
- | Less |
~ | Concatenation |
* | Multiplication |
/ | Division |
// | Division rounded to lower |
% | Modulo |
is | Test (ex: is defined or is not empty) |
** | Power |
| | filter |
[] | Array entry |
. | Attribute or method from an object (ex: country.name) |
Filters in Twig allow you to modify a variable's data before you use it. The most common use is to apply the filter when you are outputting the content. For example:
{{ post.postTitle|title }}
You can also apply filters when you assign a variable's value to another variable. Below is a simple example:
{% set firstCategory = post.categories|first %}
{{ variable|abs }}
Returns an absolute value for a number. For example, if a variable called number holds a value of -5 then {{ number|abs }} would output 5.
{{ value|base64_decode }}
Decodes a base64 encoded value.
{{ value|base64_encode }}
Base 64 encodes a value. The value must be a string.
{% for row in items|batch(3, 'No item') %} {% endfor %}
The batch filter breaks up an array into groups of arrays with the given number of items.
{{ variable|camel }}
Takes a series of words and camel cases them.
{{ variable|capitalize }}
Changes the first letter of the value to be uppercase. All other characters will be lower case.
{{ number|ceiling }}
Rounds up a number.
{{ variable|country_abbreviation }}
Gets the 2 letter country abbreviation for the variable value if the variable value is a valid country or country abbreviation.
{% set data = variable|country_data %}
Gets an array of country data for the variable value if the variable value is a valid country or country abbreviation. The array contains the following information: abbreviation: the 2 letter country abbreviation name: the full country name
{{ variable|country_name }}
Gets the full country name for the variable value if the variable value is a valid country or country abbreviation.
{{ post.publishedOnTimestamp|date('M d, Y') }}
Formats a date to a given format.
{{ post.createdOnTimestamp|time_ago }}
Gets the difference between now (or a passed date) and the date value the filter is applied to.
{% for row in items|batch(3, 'No item') %} {% endfor %}
The batch filter breaks up an array into groups of arrays with the given number of items.
{{ post.publishedOnTimestamp|date_modify('+ 1 day')|date('m/d/Y') }}
Modifies a date based on the passed modifier.
{{ post|debug }} {{ form.fields|debug('Form fields') }}
Outputs the results of a variable in a debug statement. Useful for development.
{{ form.fields|debug_email }} {{ form.fields|debug_email('Form fields') }}
Outputs the results of a variable in a debug statement specifically formatted for using in emails. Useful when developing form notification emails.
{{ variable|default('My Default Value') }}
Returns the passed default value if the variable is undefined or empty, otherwise, it returns the variable value.
{{ variable|embed_media }}
Takes a string and looks for any URLs for embeddable resources (YouTube videos for example) and using the oEmbed protocol converts the URL into the appropriate embed code.
{{ variable|escape }}
Escapes a string for final output. Useful for user-entered data where you're not sure that the data is safe.
{{ variable|escape_quotes }} {{ variable|escape_quotes('single') }} {{ variable|escape_quotes('double') }}
Escapes single and double quotes with a backslash "\". By default it will escape both double and single quotes but you can specify which one you want to escape.
{{ '/path/to/my/file.pdf'|file_basename }}
Parses the file path and returns just the basename value.
{{ '/path/to/my/file.pdf'|file_dirname }}
Parses the file path and returns just the dirname value.
{{ '/path/to/my/file.pdf'|file_name }}
Parses the file path and returns just the filename value.
link rel="icon" type="image/png" href="{{ 'favicon.ico'|file_url }}"
Prepends the CDN or S3 URL of the file to the file path.
Returns the first value of an array, hash or string.
{{ [1, 2, 3, 4]|first }}
{{ variable|float }}
Converts the value to a float number.
{{ number|floor }} {{ number|floor(2) }}
Rounds a number down. You can also specify a precision.
{{ 'I like %s and %s'|format('icecream', 'pickles') }}
Formats a string by replacing the placeholders with the specified values.
{{ htmlVariable|html2text }}
Converts an HTML string to plain text.
{{ '
All HTMl code will be converted
'|html_entities }}Converts HTML entities to their entity value.
{{ 'Only &, <, >, " and \' will be converted'|html_special_chars }}
Converts only special characters to their HTML entity. (& " ' < >)
{{ post.abstract|inject_html(' a href="' ~ post.url ~ '">Read more /a>') }}
Inserts an HTML snippet immediately before a closing block level tag (p div) or a closing span tag if they are the last HTML tag in the variable value. If they are not then the HTML snippet is simply appended to the variable value.
{{ variable|integer }}
Converts the value to an integer.
{% set myPets = ['dog', 'cat', 'snake', 'elephant', 'fish'] %} {% set yourPets = ['snake', 'camel', 'fish', 'shark'] %} {% set samePets = myPets|intersect(yourPets) %}
Returns an array containing only the values that are in both arrays.
{% set myColors = {'g': 'green', 'b': 'blue', 'y': 'yellow', 'r': 'red'} %} {% set yourColors = {'b': 'brown', 'g': 'green', 'x': 'yellow'} %} {% set sameColors = myColors|intersect_assoc(yourColors) %}
Returns an array containing only the values that are in both arrays. The array keys are also used in the comparison.
{{ array|join(' | ') }}
Concatenates the values of an array into a string, optionally separated by the passed separator.
{{ {'fruit': 'apple', 'vegetable': 'lettuce'}|json }}
Encodes the value as a complete JSON string.
{% set data = jsonString|json_decode %}
Converts a JSON string into an array of values.
{{ post.postTitle|json_encode }}
Returns the JSON representation of a value.
{{ "Bob Smith"|kebab }}
Takes a string and creates a lowercase version of it with words separated by dashes instead of spaces. Useful for creating anchor links.
{% for key in array|keys %} {% endfor %}
Returns the keys of an array.
{% set myColors = {'blue': '5', 'red': '15', 'green': '2'} %} {% set yourColors = {'red': '2', 'black': '3', 'green': '30'} %} {% set same = myColors|kintersect(yourColors) %}
Returns an array containing only the values that are in the first array whose keys are also in the second array. The values are not compared.
{% set array = {1: 'One', 2: 'Two', 3: 'Three', 'four': 'Four string'} %} {% set array2 = {1: 'One2', 2: 'Two2', 4: 'Four', 5: 'Five'} %} {% set array = array|kmerge(array2) %}
Merges two arrays together while preserving their keys (including numeric keys).
{% set array = {1: 'One', 2: 'Two', 3: ['Three', 'Three is great'], 'four': 'Four string', 'five': {32: 'numeric key', 'string': 'string key'}} %} {% set array2 = {2: 'New Two', 3: ['Another three'], 'four': 'New Four string', 'five': {32: 'new numeric key'}, 'six': 'I will stay'} %} {% set array = array|kmerge_deep(array2) %}
Merges two arrays together recursively while preserving their keys (including numeric keys).
{% set array = array|krsort %}
Sorts an array or hash by its keys in reverse order (Z-A).
{% set array = array|ksort %}
Sorts an array or hash by its keys.
{{ [1, 2, 3, 4]|last }}
Returns the last element of an array, hash or string.
{{ variable|lcfirst }}
Lowercases the first letter of a string
{{ post.postTitle|length }}
Returns the number of items in an array or hash, or the length of a string.
{{ post.postTitle|length }}
Returns the number of items in an array or hash, or the length of a string.
{{ 'I SHOULD BE LOWERCASE'|lower }}
Converts the string value to all lower case.
{{ string|ltrim }}
Returns the number of items in an array or hash, or the length of a string.
{{ post.postTitle|length }}
Trims the begining of a string for whitespace or a specific character.
{% set hash = post.postTitle|md5 %}
Converts the string to an MD5 hash.
{% set data = ['apple', 'bannana', 'orange']|merge(['grapes', 'pinapple']) %}
Merges an array with another array.
{% set array = {1: 'One', 2: 'Two', 3: ['Three', 'Three is great'], 'four': 'Four string', 'five': {32: 'numeric key', 'string': 'string key'}} %} {% set array2 = {1: 'One2', 2: 'Two2', 4: 'Four', 5: 'Five'} %} {% set array = array|merge_deep(array2) %}
Merges two arrays together recursively.
{{ 3024.2|number_format(2) }}
Formats a number to have a certain number of decimal points, a specific decimal point character, and thousands separator.
{{ variable|pascal }}
Takes a series of words and PascalCases them.
{% autoescape %} {{ var|raw }} {% endautoescape %}
Marks a value as "safe" meaning it won't be auto escaped.
{% set new = ['x', 'y', 'z', 'm', 'e', '3', '10']|regex_filter(['/\\d/', '/[x-z]/'], ['$0 is a NUMBER ', '$0 is a LETTER ']) %}
Replaces values within a string by a regular expression and returns only the (possibly transformed) subjects where there was a match.
{{ 'I like %this% and %that%.'|replace({'%this%': 'apples', '%that%': 'bananas'}) }} {{ variable|replace({'-': '%ndash;'}) }} {{ 'Hi my name is Bob'|replace('Bob', 'Sam') }}
Replaces the specified text or placeholders with other values.
{% for post in posts|reverse %} {% endfor %}
Reverses an array, hash or string.
{% set newValue = value|shuffle %}
Randomizes the order of elements in an array.\ and returns the result.
{% for i in [1, 2, 3, 4]|slice(1, 2) %} {% endfor %}
Extracts a slice of an array, hash or string.
{% set array = array|sort %}
Sorts an array.
{{ post.abstract|striptags }}
Strips HTML tags from the string. The striptags filter strips SGML/XML tags and replace adjacent whitespace by one space.
{{ 'Hello Stack Exchange!'|t }}
The t filter only allows for simple strings transalations.
{% trans %}Hello {{ user.name }}, today's date is {{ date|placeholder }}.{% endtrans %}
%trans block allows the use of dynamic placeholders in the string. Much like using the php t() function.
{{ post.plainDescription|text2html }}
Converts a plain-text string to HTML characters. Newline characters are converted to
tags. URL are also converted to links.
link rel="stylesheet" href="{{ 'css/index.css'|theme_url }}"
Prepends the URL of the theme asset with the theme path. This is useful when using images, CSS or Javascript theme assets in the theme templates. It ensure that if the path to the theme changes then the links to the theme assets won't be broken.
{{ post.publishedOnTimestamp|time('H:i A') }}
Formats a timestamp to a given time format.
{{ post.postTitle|title }}
Converts a string to have the first letter of each word capitalized and all other characters lower case.
{{ var|truncate(20) }}
Shortens a string to the specified length. This does not take HTML tags into consideration.
{{ post.content|truncate_html(100) }}
Shortens a string to a specified length and ensures that the HTML does not get broken.
{% set unique = arrayVariable|unique %}
Gets the unique values from an array.
{{ post.postTitle|upper }}
Converts a string so that all characters are uppercase.