Your comprehensive guide for ERB front-end view templates.
ERB and Twig Cross-Reference for Front-End Development
Last Updated
A version of this article appeared on viget.com
Read more
This post is geared towards developers who want to translate their Twig knowledge to ERB, or vice versa. If you’re only interested in one language or the other, check out Fundamental ERB for Front-End Development or Fundamental Twig for Front-End Development.
Contents
Introduction
Twig and ERB are the two front-end templating languages I use most when developing websites. Here I document the ways each write just about everything to build views: comments, conditionals, variables and undefined variables, interpolation, loops and the loop index, slicing, handling whitespace, retrieving an keyed values, and templating with blocks and partials. If you’re familiar with one of Twig or ERB, use this as a cross-reference to translate your knowledge of the one language into the other. If you haven’t used either, this should get you up and running quickly. Read on to learn more about ERB and Twig, or skip ahead to the reference section.
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.
What is ERB?
ERB (Embedded Ruby) is a feature of Ruby that lets you —you guessed it!— embed Ruby in other files. ERB files have the extension .<compiled_extension>.erb
. It is the language HAML and Slim are shorthand for. ERB is commonly used for templating Views in Rails apps.
Because it can do anything Ruby can do, it’s extremely powerful, has a much steeper learning curve than Twig, and can do a lot that isn’t relevant to front-end templating. There’s no cannonical ERB-for-front-end-developers documentation, and the Rails official documentation is immense and hard to dig through. Some resources if for learning ERB:
- APIdock’s ActionView::Layouts and their documentation for the “included modules” listed under ActionView::Helpers (the UrlHelper’s
link...
andbutton_to
methods are essential. - The APIdock TagHelper’s documentation for the
content tag
andtag
methods are useful. - If you’re building forms familiarize yourself with the methods of the FormHelper, FormTagHelper, and FormOptionsHelper) (some will prefer the appearance of DevDocs — c.f. their ActionView and ActionView/Helpers documentation).
- LaunchSchool’s Loops & Iterators is a good resource for understanding loops in Ruby.
- Mix & Go’s How to use link_to in Rails is helpful for understanding
link_to
- RailsGuides’ Action View Overview and Layouts and Rendering in Rails cover Rails views in depth, with clear examples.
Reference
Delimiters
Comments
Inline comments
-
ERB:
<%# … %>
-
Twig:
{# … #}
Block comments
-
ERB:
=begin
…=end
the opening and closing tags must be at the start of the line
not
-
Twig:
{# … #}
or
Outputting values
-
ERB:
<%= … %>
-
Twig:
{{ }}
Execution (Control Code)
-
ERB:
<% … %>
-
Twig:
{% … %}
Conditionals
Single-statement conditionals
-
ERB:
if
andunless
Multi-statement conditionals
-
ERB:
if
…elsif
…end
-
Twig:
if
…elseif
…endif
Conditionals with logical operators
Both ERB and Twig support “condition ?
iftrue :
iffalse”, and “ifselftrue ?:
otherwise”.
-
ERB. Note that the “then” case
:
must be provided -
Twig
Truth and falsity of zero in Boolean contexts
-
ERB:
0
isTrue
in Boolean contexts -
Twig: as in PHP generally,
0
isFalse
in Boolean contexts
Defining variables
-
ERB:
=
-
Twig:
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
-
ERB: multi-line blocks of markup can stored in an identifier with
content_for x do
…end
Note:
content_for
is additive: each time you provide content for a given variable, that content is appeneded to what was there already. To usecontent_for
to overwrite a global variable, use theflush: true
option: -
Twig: use the
set
tag’s formset x
…endset
to capture chunks of text
Dealing with undefined variables
-
ERB:
-
defined?()
-
||=
, the OR Equal operator
-
-
Twig:
-
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
-
ERB:
#{var}
-
Twig:
#{var}
Concatenation
-
ERB:
+
(plus). Note that to concatenate a string and a number in Ruby, the number must be converted to a string. -
Twig:
~
(tilde). Note that strings and numbers can be freely concatenated.
Iteration (loops)
Iterating over items
-
ERB:
n.each do |i|
…end
-
Twig:
for i in n
…endfor
Using the loop index, 0-indexed
-
ERB:
-
n.each_with_index do |i, index|
…end
-
n.times do |i|
…end
-
-
Twig:
loop.index0
Using the loop index, 1-indexed
-
ERB:
-
.each_with_index
’sindex
is always 0-indexed, so add1
-
n.times do |i|
…end
-
-
Twig:
loop.index
Iterating a certain number of times
-
ERB:
n.times do |i|
…end
-
Twig:
for i in n
…endfor
Inspecting data
-
ERB: several options for formatting an object’s data, notably: simply outputting,
.inspect
ing, anddebug()
ing. For basic data-checking purposes in a view, the essential difference isdebug()
returns YAML whileinspect
and printing return strings. -
Twig:
-
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
-
ERB:
.slice(index)
,.slice(start,count)
-
Twig:
|slice(start,count)
or[start:count]
Note: The output of the above Twig examples is
Array
, because in Twig the output of{{ [anArray] }}
isArray
. If you need to print an array, use|json_encode
:In execution, no special steps are necessary:
Shorthand to slice the first count
items
-
ERB:
.take(count)
or.first(count)
-
Twig:
[:count]
Shorthand for everything after the start
item
-
Twig:
[start:]
Trimming whitespace
-
ERB
If
trim_mode
is set to-
, a-
in the closingerb
tag will trim trailing whitespace:is equivalent to
-
Twig
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
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
-
ERB:
Use a Symbol
:property
to look up an operation on a Hash: -
Twig:
Use dot notation or subscript syntax to access attributes of a variable:
Vertical inheritance
For a layout
file that pulls in page
:
-
ERB:
content_for
in child,yield
in parentlayouts/layout.html.erb
views/page.html.erb
-
Twig:
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
-
ERB
layouts/layout.html.erb
views/page.html.erb
-
Twig
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
-
ERB:
render
will output the contents of another fileTo pass values to the rendered file, define them:
If the rendered file expects different variable names, use those:
-
Twig:
-
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 withonly
): -
Articles You Might Enjoy
-
Fundamental ERB for Front-End Development
-
Fundamental Twig for Front-End Development
Your comprehensive guide for Twig front-end view templates.
-