Language: Embedded Ruby (ERB) template syntax (2024)

ERB is a templating language based on Ruby. Puppet can evaluate ERB templates with the template and inline_template functions.

This page covers how to write ERB templates. See Templates for information about what templates are and how to evaluate them.

Note: If you’ve used ERB in other projects, it might have had different features enabled. This page describes how ERB works in Puppet.

ERB structure and syntax

<%# Non-printing tag ↓ -%><% if @keys_enable -%><%# Expression-printing tag ↓ -%>keys <%= @keys_file %><% unless @keys_trusted.empty? -%>trustedkey <%= @keys_trusted.join(' ') %><% end -%><% if @keys_requestkey != '' -%>requestkey <%= @keys_requestkey %><% end -%><% if @keys_controlkey != '' -%>controlkey <%= @keys_controlkey %><% end -%><% end -%>

An ERB template looks like a plain-text document interspersed with tags containing Ruby code. When evaluated, this tagged code can modify text in the template.

Puppet passes data to templates via special objects and variables, which you can use in the tagged Ruby code to control the templates’ output.

ERB has two tags for Ruby code, a tag for comments, and a way to escape tag delimiters.

  • <%= EXPRESSION %> — Inserts the value of an expression.
    • With -%> — Trims the following line break.
  • <% CODE %> — Executes code, but does not insert a value.
    • With <%- — Trims the preceding indentation.
    • With -%> — Trims the following line break.
  • <%# COMMENT %> — Removed from the final output.
    • With -%> — Trims the following line break.
  • <%% or %%> — A literal <% or %>, respectively.

Text outside a tag becomes literal text, but it is subject to any tagged Ruby code surrounding it. For example, text surrounded by a tagged if statement only appears in the output if the condition is true.

Expression-printing tags

<%= @fqdn %>

An expression-printing tag inserts values into the output. It starts with an opening tag delimiter and equals sign (<%=) and ends with a closing tag delimiter (%>). It must contain a snippet of Ruby code that resolves to a value; if the value isn’t a string, it will be automatically converted to a string using its to_s method.

For example, to insert the value of the $fqdn and $hostname facts in an Apache config file, you could do something like:

ServerName <%= @fqdn %>ServerAlias <%= @hostname %>

Space trimming

You can trim line breaks after expression-printing tags by adding a hyphen to the closing tag delimiter.

  • -%> — If the tag ends a line, trim the following line break.

Non-printing tags

<% if @broadcastclient == true %> ...text... <% end %>

A non-printing tag executes the code it contains, but doesn’t insert a value into the output. It starts with an opening tag delimiter (<%) and ends with a closing tag delimiter (%>).

Non-printing tags that contain iterative or conditional expressions can affect the untagged text they surround.

For example, to insert text only if a certain variable was set, you could do something like:

 <% if @broadcastclient == true -%> broadcastclient <% end -%>

Non-printing code doesn’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 statement. For example, you couldn’t write:

<%# 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 method call and its required block.

Space trimming

You can trim whitespace surrounding a non-printing tag by adding hyphens (-) to the tag delimiters.

  • <%- — If the tag is indented, trim the indentation.
  • -%> — If the tag ends a line, trim the following line break.

<%# This is a comment. %>

A comment tag’s contents do not appear in the template’s output. It starts with an opening tag delimiter and a hash sign (<%#) and ends with a closing tag delimiter (%>).

Space trimming

You can trim line breaks after comment tags by adding a hyphen to the closing tag delimiter.

  • -%> — If the tag ends a line, trim the following line break.

Literal tag delimiters

If you need the template’s final output to contain a literal <% or %>, you can escape them 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 %>.

Accessing Puppet variables

Templates can access Puppet’s variables. This is the main source of data for templates.

An ERB template has its own local scope, and its parent scope is set to the class or defined type that evaluates the template. This means a template can use short names for variables from that class or type, but it can’t insert new variables into it.

There are two ways to access variables in an ERB template:

  • @variable
  • scope['variable'] (and its older equivalent, scope.lookupvar('variable'))

@variable

All variables in the current scope (including global variables) are passed to templates as Ruby instance variables, which begin with “at” signs (@). If you can access a variable by its short name in the surrounding manifest, you can access it in the template by replacing its $ sign with an @. So $os becomes @os, $trusted becomes @trusted, etc.

This is the most legible way to access variables, but it doesn’t support variables from other scopes. For that, you need to use the scope object.

scope['variable'] or scope.lookupvar('variable')

Puppet also passes templates an object called scope, which can access all variables (including out-of-scope ones) with a hash-style access expression. For example, to access $ntp::tinker you would use scope['ntp::tinker'].

There is also another way to use the scope object: you can call its lookupvar method and pass the variable’s name as its argument, like scope.lookupvar('ntp::tinker'). This is exactly equivalent to the above, but slightly less convenient. It predates the hash-style indexing, which was added in Puppet 3.0.

Puppet data types in Ruby

Puppet’s data types are converted to Ruby classes as follows:

Puppet type Ruby class
Boolean Boolean
Undef NilClass (value nil)
String String
Number subtype of Numeric
Array Array
Hash Hash
Default Symbol (value :default)
Regexp Regexp
Resource reference Puppet::Pops::Types::PResourceType, or Puppet::Pops::Types::PHostClassType
Lambda (code block) Puppet::Pops::Evaluator::Closure
Data type (Type) A type class under Puppet::Pops::Types, such as Puppet::Pops::Types::PIntegerType

Testing for undefined variables

If a Puppet variable was never defined, its value is undef, which means its value in a template will be nil.

Some basic Ruby for ERB templates

To manipulate and print data in ERB templates, you’ll need to know a small amount of Ruby. We can’t teach that on this page, but we can give a brief look at some of the things you’re likely to use.

if statements

Ruby’s if ... end statement lets you write conditional text. You’ll want to put the control statements in non-printing tags, and the conditional text between the tags. (Like <% if <CONDITION> %> text goes here <% end %>.)

<% if @broadcast != "NONE" %>broadcast <%= @broadcast %><% end %>

The general format of an if statement is:

if <CONDITION> ... code ...elsif <CONDITION> ... other code ...end

Iteration

Ruby lets you iterate over arrays and hashes with the each method. This method takes a block of code, and executes it once for each element in the array or hash. In a template, un-tagged text is treated as part of the code that gets repeated. (It might help to think of literal text as an instruction, telling the evaluator to insert that text into the final output.)

To write a block of code in Ruby, use either do |arguments| ... end or {|arguments| ... }. Note that this is different from Puppet’s lambdas — but they work similarly.

<% @values.each do |val| -%>Some stuff with <%= val %><% end -%>

If $values was set to ['one', 'two'], this example would produce:

Some stuff with oneSome stuff with two

This example also trims line breaks for the non-printing tags, so they won’t appear as blank lines in the output.

Manipulating data

Usually, your templates will use data from Puppet variables. These values will almost always be strings, numbers, arrays, and hashes.

These will become the equivalent Ruby objects when you access them from an ERB template. For information about the ways you can transform these objects, see the Ruby documentation for:

Also, note that Puppet’s special undef value becomes Ruby’s special nil value in ERB templates.

Calling Puppet functions from templates

You can use Puppet functions inside templates with the scope.call_function(<NAME>, <ARGS>) method. This method takes two arguments:

  • The name of the function, as a string.
  • All arguments to the function, as an array. (This must be an array even for one argument or zero arguments.)

For example, to evaluate one template inside another:

<%= scope.call_function('template', ["my_module/template2.erb"]) %>

To log a warning using Puppet’s own logging system, so that it will appear in reports:

<%= scope.call_function('warning', ["Template was missing some data; this config file might be malformed."]) %>

Note: Previous versions of Puppet handled this by creating a function_<NAME> method on the scope object for each function; these could be called with an arguments array, like <%= scope.function_template(["my_module/template2.erb"]) %>

That still works in this version of Puppet, but the call_function method is better. The auto-generated methods don’t support the modern function APIs, which are now used by the majority of built-in functions.

scope.call_function was added in Puppet 4.2.

Example template

This example template is taken from the puppetlabs/ntp module.

# ntp.conf: Managed by puppet.#<% if @tinker == true and (@panic or @stepout) -%># Enable next tinker options:# panic - keep ntpd from panicking in the event of a large clock skew# when a VM guest is suspended and resumed;# stepout - allow ntpd change offset fastertinker<% if @panic -%> panic <%= @panic %><% end %><% if @stepout -%> stepout <%= @stepout %><% end %><% end -%><% if @disable_monitor == true -%>disable monitor<% end -%><% if @disable_auth == true -%>disable auth<% end -%><% if @restrict != [] -%># Permit time synchronization with our time source, but do not# permit the source to query or modify the service on this system.<% @restrict.flatten.each do |restrict| -%>restrict <%= restrict %><% end -%><% end -%><% if @interfaces != [] -%># Ignore wildcard interface and only listen on the following specified# interfacesinterface ignore wildcard<% @interfaces.flatten.each do |interface| -%>interface listen <%= interface %><% end -%><% end -%><% if @broadcastclient == true -%>broadcastclient<% end -%># Set up servers for ntpd with next options:# server - IP address or DNS name of upstream NTP server# iburst - allow send sync packages faster if upstream unavailable# prefer - select preferrable server# minpoll - set minimal update frequency# maxpoll - set maximal update frequency<% [@servers].flatten.each do |server| -%>server <%= server %><% if @iburst_enable == true -%> iburst<% end %><% if @preferred_servers.include?(server) -%> prefer<% end %><% if @minpoll -%> minpoll <%= @minpoll %><% end %><% if @maxpoll -%> maxpoll <%= @maxpoll %><% end %><% end -%><% if @udlc -%># Undisciplined Local Clock. This is a fake driver intended for backup# and when no outside source of synchronized time is available.server 127.127.1.0fudge 127.127.1.0 stratum <%= @udlc_stratum %>restrict 127.127.1.0<% end -%># Driftfile.driftfile <%= @driftfile %><% unless @logfile.nil? -%># Logfilelogfile <%= @logfile %><% end -%><% unless @peers.empty? -%># Peers<% [@peers].flatten.each do |peer| -%>peer <%= peer %><% end -%><% end -%><% if @keys_enable -%>keys <%= @keys_file %><% unless @keys_trusted.empty? -%>trustedkey <%= @keys_trusted.join(' ') %><% end -%><% if @keys_requestkey != '' -%>requestkey <%= @keys_requestkey %><% end -%><% if @keys_controlkey != '' -%>controlkey <%= @keys_controlkey %><% end -%><% end -%><% [@fudge].flatten.each do |entry| -%>fudge <%= entry %><% end -%><% unless @leapfile.nil? -%># Leapfileleapfile <%= @leapfile %><% end -%>
Language: Embedded Ruby (ERB) template syntax (2024)

FAQs

What is ERB language? ›

ERB stands for Embedded Ruby, and is used to insert Ruby variables inside templates, e.g. HTML and YAML. ERB is a Ruby class that accepts text, and evaluates and replaces Ruby code surrounded by ERB markup.

What is ERB file in Ruby? ›

ERB (Embedded RuBy) is a feature of Ruby that enables you to conveniently generate any kind of text, in any quantity, from templates. The templates themselves combine plain text with Ruby code for variable substitution and flow control, which makes them easy to write and maintain.

What is ERB HTML? ›

ERB is a templating engine. A templating engine allows you to mix HTML & Ruby so you can generate web pages using data from your database. ERB is Rails default engine for rendering views. Note: Rails uses an implementation called erubi instead of the ERB class from the Ruby standard library.

What are Ruby templates? ›

Template Method is a behavioral design pattern that allows you to defines a skeleton of an algorithm in a base class and let subclasses override the steps without changing the overall algorithm's structure.

Can Ruby be embedded into HTML? ›

So far we've looked at using Ruby to create HTML output, but we can turn the problem inside out; we can actually embed Ruby in an HTML document. There are a number of packages that allow you to embed Ruby statements in some other sort of a document, especially in an HTML page.

What is JSON ERB? ›

json. erb is basically the raw json response but with some parts evaluated in ruby. For example, this is a valid json. erb, that produces valid json: { "status" : "success!" }

How do I create a Rails template? ›

Rails Application Templates - YouTube

What is a layout template? ›

A design template or template is a file created with an overall layout to be used with one or more documents. For example, a word processor may have a template for a resume. With a resume template, the overall layout is designed with placeholder text (e.g., your objective, previous job experience, etc.)

What is ERB binding? ›

ERB gets variables from a Binding, an object that provides access to the instance methods and variables that are owned by another object. If you do not specify a Binding, the result() method gets a Binding from the top-level object, which will probably own very little.

How do I read a text file in Ruby? ›

You can read the contents of the file in three ways.
...
How to Read Files In Ruby
  1. Open the file, with the open method.
  2. Read the file, the whole file, line by line, or a specific amount of bytes.
  3. Close the file, with the close method.

What are templates in Rails? ›

Application templates are simple Ruby files containing DSL for adding gems, initializers, etc. to your freshly created Rails project or an existing Rails project. After reading this guide, you will know: How to use templates to generate/customize Rails applications.

How do I comment in an ERB file? ›

To comment one line I must use 3 additional characters, and the block comment is nothing but code that will be not executed - no other color coding that makes it very unpractical to see which code is not executed on first look. @gotqn Then you will LOVE HAML!

What is puppet template? ›

Templating is a method of getting things in a standard format, which can be used in multiple locations. In Puppet, templating and templates are supported using erb which comes as a part of standard Ruby library, which can be used on other projects apart from Ruby like in Ruby on Rails projects.

What is chef template? ›

Chef uses templates to be able to fill the configuration file with dynamic values. Chef provides templates as a resource which can be used in the recipe. Configuration files' dynamic values can be retrieved from data bags, attributes or even calculate them by passing them into the template.

How does Ruby work with HTML? ›

You could use Ruby's regular expression features to parse incoming query strings, look up environment variables, check tags, substitute text into templates, escape special characters, format up the HTML, and print it all out. Or, you could use class CGI .

What is Gemfile and Gemfile lock? ›

The Gemfile is where you specify which gems you want to use, and lets you specify which versions. The Gemfile. lock file is where Bundler records the exact versions that were installed. This way, when the same library/project is loaded on another machine, running bundle install will look at the Gemfile.

How do I parse a JSON file in Ruby? ›

If you don't have already installed JSON gem on your computer you can install it running the following command.
  1. gem install json.
  2. require 'json' => true.
  3. file = File.read('./file-name-to-be-read.json')
  4. data_hash = JSON.parse(file)
May 21, 2020

How do you parse a JSON object in Ruby? ›

  1. Also you can sets the option symbolize_names to true, in order to get keys as symbols. Exemple: JSON.parse(string, symbolize_names: true) #=> {key: :value} ...
  2. JSON is directly supported in Ruby, and has been since at least Ruby v1. 9.3, so there is no need to install a gem unless you're using something older.
Mar 23, 2011

What is JSON in Ruby? ›

JSON (JavaScript Object Notation) is a lightweight data interchange format. Many web applications use it to send and receive data. In Ruby you can simply work with JSON. At first you have to require 'json' , then you can parse a JSON string via the JSON. parse() command.

Does Ruby have generators? ›

What about Ruby? Well, the Ruby language does not have generators. It does have Fibers, which can accomplish pretty much the same thing1, but, more interestingly from a learning perspective, it has native support for continuations.

How do you generate scaffold in rails? ›

To generate a fully working scaffold for a new object, including model, controller, views, assets, and tests, use the rails g scaffold command. Then you can run rake db:migrate to set up the database table. Then you can visit http://localhost:3000/widgets and you'll see a fully functional CRUD scaffold.

How do you use yield in Ruby? ›

How Yield statement works In Ruby?
  1. Yield is a keyword in Ruby and when we want to make a call to any block then we can use the yield, once we write the yield inside any method it will assume for a blocking call.
  2. There is no limitation for passing a number of arguments to the block from yield statements.

What is a template example? ›

A template is a form, mold or pattern used as a guide to make something. Here are some examples of templates: Website design. Creating a document. Knitting a sweater.

How can I create a template? ›

Open the presentation that you want to save as a template. On the File tab, click Save as Template. In the Save As box, type the name that you want to use for the new template. (Optional) In the Where box, choose a location where the template will be saved.

What is difference between template and layout? ›

Layouts are the next level in the page model hierarchy, below templates. Whereas a template defines all the modules that are allowed for a page, a layout is an explicit selection and arrangement of modules. Pages are the next level in the page model hierarchy, below layouts.

What is binding in Ruby? ›

To keep track of the current scope, Ruby uses bindings, which encapsulate the execution context at each position in the code. The binding method returns a Binding object which describes the bindings at the current position.

What are ERB files used for? ›

ERB files contain source code written in a programming language of the same name. The ERB language is essentially a Ruby templating language. ERB files are saved in a plain text format which allows them to be opened in any text editing program. Thus, the file can contain any type of text alongside the ERB source code.

What is ERB binding? ›

ERB gets variables from a Binding, an object that provides access to the instance methods and variables that are owned by another object. If you do not specify a Binding, the result() method gets a Binding from the top-level object, which will probably own very little.

How do I comment in an ERB file? ›

To comment one line I must use 3 additional characters, and the block comment is nothing but code that will be not executed - no other color coding that makes it very unpractical to see which code is not executed on first look. @gotqn Then you will LOVE HAML!

What is binding in Ruby? ›

To keep track of the current scope, Ruby uses bindings, which encapsulate the execution context at each position in the code. The binding method returns a Binding object which describes the bindings at the current position.

How do I read a text file in Ruby? ›

You can read the contents of the file in three ways.
...
How to Read Files In Ruby
  1. Open the file, with the open method.
  2. Read the file, the whole file, line by line, or a specific amount of bytes.
  3. Close the file, with the close method.

What are templates in Rails? ›

Application templates are simple Ruby files containing DSL for adding gems, initializers, etc. to your freshly created Rails project or an existing Rails project. After reading this guide, you will know: How to use templates to generate/customize Rails applications.

What is puppet template? ›

Advertisem*nts. Templating is a method of getting things in a standard format, which can be used in multiple locations. In Puppet, templating and templates are supported using erb which comes as a part of standard Ruby library, which can be used on other projects apart from Ruby like in Ruby on Rails projects.

How do I comment code in Ruby? ›

The Ruby single-line comment begins with the # character and ends at the end of the line. Any characters from the # character to the end of the line are completely ignored by the Ruby interpreter. The # character doesn't necessarily have to occur at the beginning of the line; it can occur anywhere.

How do you comment multiple lines in Ruby? ›

Despite the existence of =begin and =end , the normal and a more correct way to comment is to use # 's on each line. If you read the source of any ruby library, you will see that this is the way multi-line comments are done in almost all cases.

What are magic comments Ruby? ›

Magic Comments. While comments are typically ignored by Ruby, special “magic comments” contain directives that affect how the code is interpreted. Top-level magic comments must appear in the first comment section of a file. NOTE: Magic comments affect only the file in which they appear; other files are unaffected.

What is Attr_accessor in Ruby? ›

Nouman Abbasi. In Ruby, object methods are public by default, while data is private. To access and modify data, we use the attr_reader and attr_writer . attr_accessor is a shortcut method when you need both attr_reader and attr_writer .

What is eval in Ruby? ›

eval. The eval method of Kernel allows you to evaluate a string in the current context. The eval method also allows you to optionally specify a binding. If a binding is given, the evaluation will be performed in the context of the binding.

What is variable scope in Ruby? ›

What is Variable Scope? Scope defines where in a program a variable is accessible. Ruby has four types of variable scope, local, global, instance and class. In addition, Ruby has one constant type.

Top Articles
Latest Posts
Article information

Author: Annamae Dooley

Last Updated:

Views: 6443

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Annamae Dooley

Birthday: 2001-07-26

Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

Phone: +9316045904039

Job: Future Coordinator

Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.