ERB tags
Embedded Ruby (ERB) has two tags for Ruby code expressions, a tag for comments, and a way to escape tag delimiters.
The following table provides an overview of the main tag types used with ERB. See the sections below for additional detail about each tag, including instructions on trimming whitespace and escaping special characters.
I want to ... | ERB tag syntax |
---|---|
Insert the value of a single expression. | <%= EXPRESSION
%> |
Execute an expression without inserting a value. | <% EXPRESSION
%> |
Add a comment. | <%# COMMENT
%> |
if
statement only
appears in the output if the condition is true.
Expression-printing tags
An expression-printing tag inserts the value into the output.
Opening tag | <%= |
Closing tag | %> |
Closing tag with trailing whitespace and line break trimming | -%> |
<%= @networking['fqdn'] %>It must contain a snippet of Ruby code that resolves to a value; if the value isn’t a string, it is automatically converted to a string using its
to_s
method.
For example, to insert the value of the fqdn
and hostname
facts in an ERB template for an Apache config file:
ServerName <%= @networking['fqdn'] %> ServerAlias <%= @networking['hostname'] %>
Non-printing tags
A non-printing tag executes the code it contains, but doesn’t insert a value into the output.
Opening tag | <% |
Opening tag with indentation trimming | <%- |
Closing tag | %> |
Closing tag with trailing whitespace and line break trimming | -%> |
For example, to insert text only if a certain variable was set, write:
<% if @broadcastclient == true -%> broadcastclient <% end -%>
Expressions in non-printing tags don’t have to resolve to a value or be a complete statement, but the tag must close at a place where it would be legal to write another expression. For example, this doesn't work:
<%# Syntax error: %> <% @servers['each'] -%> # some server <% do |server| %>server <%= server %> <% end -%>
You must keep do |server|
inside the first tag, because
you can’t insert an arbitrary statement between a function call and its required
block.
Comment tags
A comment tag’s contents do not appear in the template's output.
Opening tag | <%# |
Closing tag | %> |
Closing tag with line break trimming | -%> |
<%# This is a comment. %>
Literal tag delimiters
If you need the template’s final output to contain a literal <%
or %>
, you can escape the
characters as <%%
or %%>
. The first literal tag is taken, and the rest of the line is treated
as a literal. This means that <%% Test %%>
in an
ERB template would turn out as <% Test %%>
, not
<% Test %>
.