Embedded Ruby (abbreviated as ERB or eRuby) is a template engine that embeds Ruby code into text documents. It is commonly used to generate dynamic content in HTML documents, which is a role similar to Active Server Pages, JavaServer Pages, PHP, and other server-side scripting languages. eRuby combines Ruby code and plain text to provide flow control and variable substitution, thus making the combined code easier to maintain.[1]
| eRuby | |
|---|---|
| Other names | ERB |
| Written in | Ruby |
| Type | Template engine |
| License | BSD 2-Clause License |
| Repository | github |
In Ruby on Rails, eRuby is commonly used in a view layer in order to generate dynamic web content. The view module of Ruby on Rails is responsible for displaying a response or output in a browser. In its simplest form, a view may consist of static HTML content; however, many Ruby on Rails applications will require dynamic content created by the controller (an action method) to be displayed in their view. This is achieved from Embedded Ruby templates, which allow Ruby code to be embedded within view documents.
During rendering, the embedded code is evaluated and replaced with its resulting value at runtime. However, the ability to embed code in a view document risks bridging the clear separation present in the MVC frame. As a result, maintaining clear separation of responsibility among the model, view, and controller modules is left to the developer of the application.[2]
Usage
editeRuby embeds Ruby code within a pair of <% and %> delimiters, which are then evaluated in-place. Apart from creating web pages, eRuby can also be used to create XML Documents, RSS feeds, and other forms of structured text files. Moreover, eRuby dynamically generates static files based on templates. These functionalities of eRuby can be found in the ERB Library.
There are different types of tag markers used in ERB templates:
- Expression tags
- Execution tags
- Comment tags[3]
Expression tags
editThe delimiter <%= %> indicates that the tag encloses an expression. Such tag starts with an opening tag delimiter followed by an equal to symbol, and ends with an end tag delimiter. During the rendering of the template, this piece of code gets substituted with the result of the code. If the evaluated result is not a string, it gets converted to a string before it is rendered.[1]
require 'erb'
x = 500
template = ERB.new("The value of x is: <%= x %>")
puts template.result(binding)
<%# Output: The value of x is: 500 %>
Execution tags
editExecution tags are defined by <% %> and code enclosed in such tags is called a scriptlet. The code in the respective tag gets executed, and its result gets replaced in place of the scriptlet. Such tags require a matching <% end %> tag to denote the end of a functional block. The following ERB template generates an HTML list item four times:[4]
<ul>
<% 4.times do %>
<li>list item</li>
<% end %>
</ul>
The following is the resulting output:
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
As shown from the output, the text list item is printed four times. The scriptlet produces no text on its own; it only makes the enclosed statement to run multiple times.
Comments tags
editComments are defined with the tag <%# %> and do not get rendered in the output. Such tags start with an open tag delimiter followed by a hash symbol and end with an end tag delimiter. The following is an example of a comment tag:[5]
<%# ruby code %>
Ruby uses the same comment tags as eRuby, and all code after # is ignored, thereby generating nothing.
Other tags
editThere are other tags common in both eRuby and Ruby, such as string substitution with #{string_name}, which is similar in languages such as Perl or PHP.
Newlines in eRuby can be suppressed by adding a hyphen at the beginning of a end tag delimiter.
The following is an example of the value of @name getting printed twice in the same line:[1][3]
<% 2.times do -%>
<%= @name %>
<% end -%>
Implementations
editThere are several implementations of eRuby:
- ERB
- erubis
- ember
erb
editerb is an implementation of eRuby written purely in the Ruby programming language and included in the Ruby standard library.[2]
A template can be generated by running a piece of code written using the ERB object. A simple example is as follows:
require 'erb'
x = 400
simple_template = "Value of x is: is <%= x %>."
renderer = ERB.new(simple_template)
puts output = renderer.result(binding)
<%# Output: Value of x is: 400 %>
This approach differs from string interpolation, which produces the output immediately when the string is constructed:
x = 400
string = "The value of x is: #{x}"
puts string
However, constructing the string before the first variable is defined prevents the code from executing:
string = "The value of x is: #{x}"
x = 400
puts string
Thus, the primary reason for using an ERB object is to write templates ahead of time, by binding variables and methods that may not exist at the given time. The template gets processed only when result is called on the ERB object. In order to get access to instance methods and instance variable of an object, ERB makes use of a binding object.
Access to variables and methods of an object is given by the private binding object which exists in each Ruby class. It is easy to get access to methods and variables within the method of a class; however, to access variables of a different class, the class will have to expose its binding object via a public method. An example is as follows:[2][4]
class ERBExample
attr_accessor:variable1
# using bind to access class variables
def render()
renderer.result(binding)
end
def initialize(variable1)
@variable1 = variable1
end
# Expose private binding() method.
def get_binding
binding()
end
end
example = ERBExample.new(variable1)
renderer = ERB.new(template)
puts output = renderer.result(example.get_binding)
As shown, the binding object of the class ERBExample is exposed. Furthermore, the binding object is used to access the variables and methods of the class within one of its methods.
new() method of ERB
edit
The new method of the ERB object takes two more parameters. The first parameter specifies the template, and the second parameter specifies a safety level which makes the template run in a different thread. At the maximum safety level of four, ERB cannot use a binding object unless it is marked as trusted. The third parameter specifies optional modifiers, which can be used to control the adding of newlines to the output. For example, to ensure that ERB does not output newlines after tag ends, an ERB object can be created as shown below:[3][4]
renderer = ERB.new(template, 3, '>')
To only provide the third parameter and ignore the second parameter, use 0 as the input for second parameter.
ERB has many other methods exposed which can be used to render a template. A full list of APIs exposed by the ERB object is listed in the ERB documentation.
Running ERB from Command-line
editThe erb command-line provides a way to process ERB templates from the terminal.It reads a template file, evaluates embedded Ruby code, and prints the result in the output. Output redirection can be used to write the result to a file rather than printing it in standard output.[3]
erb sample1.erb.txt > my_view.html.erb
In the above example, output gets redirected to my_view.html.erb file.
Additional third-party libraries can be loaded using the -r option followed by the name of the library, which is similar to the keyword require.
The following example uses the IPAddr library:
erb -r IPAddr sample1.txt.erb > my_view.html.erb
For specifying safety levels, a number can be passed as a command-line argument using the -S option:[3]
erb -S 4 sample1.erb.txt > my_view.html.erb
erubis
editember
editDifferent implementation tags comparison
editThe below table compares the tags available in each of the above implementations:[4][7][8]
Implementations |
Simple expression tag<%= %> |
Simple execution tag<% %> |
Simple comment tag<%# %> |
Ability to configure tag pattern | Short hand notation for tags | <%~ %> |
<%+ %> |
<%< > |
<%| > |
|---|---|---|---|---|---|---|---|---|---|
erb |
Yes | Yes | Yes | No | Yes, <%xy%> can be written as %xy. |
No | No | No | No |
erubis |
Yes | Yes | Yes | Yes, can change tag pattern to anything.
ex - |
Yes,
as one can change tag patterns. |
No | No | No | No |
ember |
Yes | Yes | Yes | No | Yes, <%xy%> can be written as %xy. |
The content of the tag is evaluated as an eRuby template. | The content of the tag is evaluated as Ruby code and is expected to be a path pointing to a Ruby template file which is read, evaluated, and rendered. | Same as <%+ %> but file contents are simply rendered into the output. |
Treats the enclosed code as a block of Ruby code and (if necessary) appends a do keyword to the body of the tag. |
See also
edit- mod_ruby
- Phusion Passenger (mod_rails)
- Haml
- RDoc
- Markaby
References
edit- 1 2 3 Brown, Gregory (2009). Ruby Best Practices. O'Reilly. pp. 279–281. ISBN 978-0596523008.
- 1 2 3 S., Ruby; D., Thomas; Hansson D, Heinemeier (2011). Agile Web Development with Rails. The Pragmatic Programmers. p. 35. ISBN 978-1-934356-54-8.
- 1 2 3 4 5 Ellis, Stuart (1 July 2016). "An Introduction to ERB Templating". Retrieved 12 September 2016.
- 1 2 3 4 "ERB".
- ↑ "ERB – Ruby Templating". 2016. Retrieved 12 September 2016.
- ↑ "erubis | RubyGems.org | your community gem host". rubygems.org. Retrieved 2026-05-14.
- 1 2 "ember(1)". 29 June 2011. Retrieved 12 September 2016.
- ↑ "Erubis". 2011. Archived from the original on 27 March 2017. Retrieved 12 September 2016.
External links
edit- ERB Library
- "Ruby and the web", a chapter from "The Pragmatic Programmer's Guide"
- "web-mode.el", emacs major mode for editing eRuby templates
- ERB – Ruby Templating
- erb documentation
- Ruby standard library
- erubis documentation Archived 2017-03-27 at the Wayback Machine
- ember documentation