Twig (template engine)
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.
Features
- complex control flow
- automatic escaping
- template inheritance
- variable filters
- i18n support
- macros
- fully extendable
- Eclipse via the Twig plugin
- Komodo and Komodo Edit via the Twig highlight/syntax check mode
- NetBeans via the Twig syntax plugin
- PhpStorm
- Atom via the PHP-twig for atom
- emacs via web-mode.el
- Notepad++ via the Notepad++ Twig Highlighter
- Sublime Text via the Twig bundle
- TextMate via the Twig bundle
- vim via the Jinja syntax plugin or the vim-twig plugin
- Brackets via Brackets Twig
- Visual Studio Code via the Twig extension
- GTKSourceView via the Twig language definition
- Coda via the Twig syntax mode
- Coda 2 via the other Twig syntax mode
- SubEthaEdit via the Twig syntax mode
Syntax
-
, to print the content of variables or the result of evaluating an expression. -
, to add comments in the templates. These comments aren't included in the rendered page.
-
, to execute statements, such as for-loops.
- *
, to assign. - *
... : condition. - *
... : counter in a loop.
To create an iterative array:
An associative array:
Operators precedence
The operators precedence is, from the less to more priority:Operator | Role |
b-and | Boolean and |
b-xor | Exclusive or |
b-or | Boolean 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 |
+ | Plus |
- | Less |
~ | Concatenation |
* | Multiplication |
/ | Division |
// | Division rounded to lower |
% | Modulo |
is | Test |
** | Power |
Filter | |
Array entry | |
. | Attribute or method from an object |
Filters
The filters provide some treatments on an expression, when place after it, separated by pipes. For example:-
capitalize
: changes a string first letter in capital. -
upper
: changes a whole string in capital. -
first
: displays the first line of an array. -
length
: returns a variable size.Special variables
-
loop
contains the current loop information. For exampleloop.index
corresponds to the number of iterations which have already occurred. - The global variables begin by underscores. For example:
- * _route
- * _self
- :So, to the a page route:
- The CGI environment variables, such as
.Example