Your comprehensive guide for ERB front-end view templates.
Fundamental Twig for Front-End Development
Last Updated
Read more
This post is an iteration on ERB and Twig Cross-Reference for Front-End Development. That post is geared towards developers who want to translate their Twig knowledge to ERB, or vice versa. You may also be interested in Fundamental ERB for Front-End Development.
Contents
What is Twig?
Twig is SensioLabs’ Django- / Jinja-like templating language for PHP. The recommended extension for Twig files is .twig
, .<compiled_extension>.twig
is useful, and .html
—though inaccurate— is common in front-end templating. It’s used by SensioLabs’ Symfony; by Drupal 8, which is built on Symfony; and by Craft CMS.
Twig is a great language for building web front ends: it is full-featured without having more than one person could hope to learn, it reads fairly closely to English, and it has great official documentation. Twig is especially notable for its powerful support for complex inheritance across templates. Check out the use
tag, the embed
tag, and the block()
function.
Twig even has Javascript implementations, making it easy to fit into projects built on the JS ecosystem. A quick overview to help you pick the one that best suits yours needs:
- Mozilla’s Nunjucks is officially “jinja2 inspired” but it has [often followed Twig’s lead](https://github.com/mozilla/nunjucks/issues?utf8=✓&q=is%3Aissue is%3Aclosed twig ). If you use Gulp in your build tools, you can use gulp-nunjucks.
- Twig.js is a popular JS port of Twig that sees more active development than Nunjucks does. It does not reach full parity with Twig (as of this writing Twig.js notably still has some bugs with Twig’s
embed
tag) but it currently comes closer than Nunjucks does and, since its goal is to duplicate Twig, it likely always will. The Twig.js Gulp plugin is gulp-twig. - Twing is a Twig engine for Node.js written in TypeScript which aims to always maintain complete parity with Twig. It is described as “a maintainability-first engine that passes 100% of the TwigPHP integration tests, is as close as possible to its code structure and expose an as-close-as-possible API.” Because Twing is able to essentially reuse much of Twig’s codebase, adding new features as they are merged into Twig is straightforward. Twing is the youngest of these projects… Twig users, show it your love! gulp-twing lets you use Twing with Gulp.
To learn Twig, read through the official documentation, and try things out in twigfiddle.
Reference
Delimiters
Comments
Inline comments
{# … #}
Block comments
{# … #}
or
Outputting values
{{ }}
Execution (Control Code)
{% … %}
Conditionals
if
…elseif
…endif
With logical operators
Twig supports “condition ?
iftrue :
iffalse”, and “ifselftrue ?:
otherwise”.
Truth and falsity of zero in Boolean contexts
As in PHP, 0
is False
in Boolean contexts
Defining variables
set
Twig can define multiple variables in a single call — just keep in mind that developers not used to this might overlook the multiple declarations!
(A value must be explicitly provided for each variable: {% set x, y = 1 %}
will error.)
Line breaks within a variable’s value
Use the set
tag’s form set x
…endset
to capture chunks of text
Dealing with undefined variables
-
is defined
Especially useful when Twig’s
strict variables
option is turned on, in which case referring to an undefined variable will throw an error. -
??
, the null coalescing operator
Variable interpolation
#{var}
Concatenation
~
(tilde). Note that strings and numbers can be freely concatenated.
Iteration (loops)
Iterating over items
for i in n
…endfor
Using the loop index, 0-indexed
loop.index0
Using the loop index, 1-indexed
loop.index
Iterating a certain number of times
for i in n
…endfor
Inspecting data
-
The
|json_encode()
filter formats an object’s data. -
The
dump()
function outputs information about a variable.Note:
dump
must be enabled. Some implementations make it available out of the box (for example, Craft CMS in dev mode).
Slicing
|slice(start,count)
or [start:count]
Note: The output of the above Twig examples is Array
, because in Twig the output of {{ [anArray] }}
is Array
. If you need to print an array, use |json_encode
:
In execution, no special steps are necessary:
Shorthand to slice the first count
items
[:count]
Shorthand for everything after the start
item
[start:]
Trimming whitespace
Trim leading or trailing whitespace by adding a -
inside in an opening or close delimiter, respectively:
is equivalent to
Trimming space between HTML elements
Twig doesn’t care what language you are compiling to, but it does provide a special spaceless
tag for use with HTML.
is equivalent to
Note that this spaceless
has limited powers:
-
it isn’t recursive
is equivalent to
-
and content between HTML tags will disrupt it
is equivalent to
Keyed values
Use dot notation or subscript syntax to access attributes of a variable:
Vertical inheritance
For a layout
file that pulls in page
:
block
+ extends
in child, block
in parent.
layout.html.twig
page.html.twig
or if all the content is a variable x, page.html.twig
or if all the content is a single string, page.html.twig
or if all the content is a single literal string, page.html.twig
Vertical inheritance with default content in the parent
main.html.twig
override-content.html.twig
Result of override-content.html.twig:
override-subcontent.html.twig
Result of override-subcontent.html.twig:
Using partials
-
include
tag -
include
function
The include
tag passes the entire parent context to the included file by default:
To pass only certain data, use include with only
:
Rename variables in the with
(can be combined with only
):
Articles You Might Enjoy
-
Fundamental ERB for Front-End Development
-
-
Writing zsh tab completions can be straightforward
How I add tab completion for the zsh command line