{{Short description|Template system used with Ruby}} {{Lowercase title}} {{Infobox software | title = eRuby | name = | logo = <!-- File name without 'File:' --> | logo caption = | logo alt = | logo size = | collapsible = <!-- Any text here will collapse the screenshot. --> | screenshot = <!-- File name without 'File:' --> | screenshot size = | screenshot alt = | caption = | other_names = ERB | author = | developer = | released = <!-- {{Start date and age|YYYY|MM|DD|df=yes/no}} --> | ver layout = <!-- simple (default) or stacked --> | discontinued = <!-- Set to yes, if software is discontinued, otherwise omit. --> | latest release version = | latest release date = <!-- {{Start date and age|YYYY|MM|DD|df=yes/no}} --> | latest preview version = | latest preview date = <!-- {{Start date and age|YYYY|MM|DD|df=yes/no}} --> | repo = {{URL|https://github.com/ruby/erb}} | qid = | programming language = Ruby | middleware = | engine = <!-- or |engines= --> | operating system = | platform = | included with = | replaces = | replaced_by = | service_name = | size = | standard = | language = | language count = <!-- Number only --> | language footnote = | genre = Template engine | license = BSD 2-Clause License | website = <!-- {{URL|example.org}} or {{official URL}} --> | AsOf = }}

'''Embedded Ruby''' (abbreviated as '''ERB''' or '''eRuby''') is a template engine that embeds Ruby code into text document<nowiki/>s. 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.<ref name=":0">{{Cite book |title=Ruby Best Practices |url=https://archive.org/details/rubybestpractice00brow |url-access=limited |last=Brown |first=Gregory |publisher=O'Reilly |year=2009 |isbn=978-0596523008 |pages=[https://archive.org/details/rubybestpractice00brow/page/n296 279]–281 }}</ref>

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.<ref name=":2" />

== Usage == eRuby embeds Ruby code within a pair of <code><%</code> and <code>%></code> 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<ref name=":3">{{Cite web|url=http://www.stuartellis.eu/articles/erb/|title=An Introduction to ERB Templating|last=Ellis|first=Stuart|date=1 July 2016|access-date=12 September 2016}}</ref>

=== Expression tags ===

The delimiter <syntaxhighlight lang="erb" inline=""><%= %></syntaxhighlight> 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.<ref name=":0" /> <syntaxhighlight lang="ruby">require 'erb' x = 500 template = ERB.new("The value of x is: <%= x %>") puts template.result(binding) <%# Output: The value of x is: 500 %></syntaxhighlight> === Execution tags ===

Execution tags are defined by <syntaxhighlight lang="erb" inline=""><% %></syntaxhighlight> 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 <syntaxhighlight lang="erb" inline><% end %></syntaxhighlight> tag to denote the end of a functional block. The following ERB template generates an HTML list item four times:<ref name=":1">{{Cite web|url=https://docs.ruby-lang.org/en/master/ERB.html|title=ERB}}</ref> <syntaxhighlight lang="rhtml"> <ul> <% 4.times do %>

<li>list item</li>

<% end %> </ul> </syntaxhighlight> The following is the resulting output: <syntaxhighlight lang="html"> <li>list item</li> <li>list item</li> <li>list item</li> <li>list item</li> </syntaxhighlight>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 ===

Comments are defined with the tag <syntaxhighlight lang="erb" inline=""><%# %></syntaxhighlight> 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:<ref>{{Cite web|url=http://apidock.com/ruby/ERB|title=ERB – Ruby Templating|date=2016|access-date=12 September 2016}}</ref> <%# ruby code %> Ruby uses the same comment tags as eRuby, and all code after <code>#</code> is ignored, thereby generating nothing.

=== Other tags ===

There are other tags common in both eRuby and Ruby, such as string substitution with <code>#{string_name}</code>, 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 <code>@name</code> getting printed twice in the same line:<ref name=":0" /><ref name=":3" /> <syntaxhighlight lang="erb"> <% 2.times do -%> <%= @name %> <% end -%> </syntaxhighlight> == Implementations == There are several implementations of eRuby: # ERB # erubis # ember

=== erb === '''erb''' is an implementation of eRuby written purely in the Ruby programming language and included in the Ruby standard library.<ref name=":2">{{Cite book|title=Agile Web Development with Rails|last=S.|first=Ruby|last2=D.|first2=Thomas|last3=Hansson D|first3=Heinemeier|publisher=The Pragmatic Programmers|year=2011|isbn=978-1-934356-54-8|pages=35}}</ref>

A template can be generated by running a piece of code written using the ERB object. A simple example is as follows: <syntaxhighlight lang="ruby"> 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 %> </syntaxhighlight>

This approach differs from string interpolation, which produces the output immediately when the string is constructed:<syntaxhighlight lang="ruby"> x = 400 string = "The value of x is: #{x}" puts string </syntaxhighlight>However, constructing the string before the first variable is defined prevents the code from executing:<syntaxhighlight lang="ruby"> string = "The value of x is: #{x}" x = 400 puts string </syntaxhighlight>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:<ref name=":2" /><ref name=":1" /> <syntaxhighlight lang="ruby"> 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) </syntaxhighlight>As shown, the ''binding'' object of the class <code>ERBExample</code> is exposed. Furthermore, the ''binding'' object is used to access the variables and methods of the class within one of its methods.

==== <code>new()</code> method of ERB ==== 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:<ref name=":3" /><ref name=":1" />

<syntaxhighlight lang="ruby"> renderer = ERB.new(template, 3, '>') </syntaxhighlight>

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 [https://docs.ruby-lang.org/en/master/ERB.html ERB documentation].

====Running ERB from Command-line====

The 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.<ref name=":3" />

<syntaxhighlight lang="sh"> erb sample1.erb.txt > my_view.html.erb </syntaxhighlight>In the above example, output gets redirected to ''my_view.html.erb'' file.

Additional third-party libraries can be loaded using the <code>-r</code> option followed by the name of the library, which is similar to the keyword ''[http://apidock.com/ruby/Kernel/require <code>require</code>]''.

The following example uses the [https://docs.ruby-lang.org/en/master/IPAddr.html IPAddr] library: <syntaxhighlight lang="sh"> erb -r IPAddr sample1.txt.erb > my_view.html.erb </syntaxhighlight>

For specifying safety levels, a number can be passed as a command-line argument using the <code>-S</code> option:<ref name=":3" />

<syntaxhighlight lang="sh"> erb -S 4 sample1.erb.txt > my_view.html.erb </syntaxhighlight>

=== erubis === '''erubis''' is an implementation of eRuby implemented in Ruby and Java. It runs faster than eRuby and ERb and has several useful options, including alternate tags allowing for valid XML.<ref>{{Cite web |title=erubis {{!}} RubyGems.org {{!}} your community gem host |url=https://rubygems.org/gems/erubis/versions/2.7.0 |access-date=2026-05-14 |website=rubygems.org}}</ref>

=== ember === '''ember''' is a pure Ruby implementation of eRuby for Linux. It allows debugging of eRuby templates, improves their composability, and provides powerful shorthand eRuby directives.<ref name=":4" />

== Different implementation tags comparison == The below table compares the tags available in each of the above implementations:<ref name=":1" /><ref name=":4">{{Cite web|url=http://snk.tuxfamily.org/lib/ember/|title=ember(1)|date=29 June 2011|access-date=12 September 2016}}</ref><ref>{{Cite web|url=http://www.kuwata-lab.com/erubis/users-guide.html|title=Erubis|date=2011|access-date=12 September 2016|archive-date=27 March 2017|archive-url=https://web.archive.org/web/20170327220927/http://www.kuwata-lab.com/erubis/users-guide.html|url-status=dead}}</ref> {| class="wikitable" ! {{verth|va=middle|Implementations}} !Simple expression tag<br/><syntaxhighlight lang="erb" inline><%= %></syntaxhighlight> !Simple execution tag<br/><syntaxhighlight lang="erb" inline><% %></syntaxhighlight> !Simple comment tag<br/><syntaxhighlight lang="erb" inline><%# %></syntaxhighlight> !Ability to configure tag pattern !Short hand notation for tags !<syntaxhighlight lang="erb" inline><%~ %></syntaxhighlight> !<syntaxhighlight lang="erb" inline><%+ %></syntaxhighlight> !<syntaxhighlight lang="erb" inline><%< ></syntaxhighlight> !<syntaxhighlight lang="erb" inline><%| ></syntaxhighlight> |- ! {{verth|va=middle|erb}} | {{yes}} | {{yes}} | {{yes}} | {{no}} | {{yes}}, <syntaxhighlight lang="erb" inline><%xy%></syntaxhighlight> can be written as <code>%xy</code>. | {{no}} | {{no}} | {{no}} | {{no}} |- ! {{verth|va=middle|erubis}} | {{yes}} | {{yes}} | {{yes}} | {{yes}}, can change tag pattern to anything.

ex - <code>[% %]</code> etc. | {{yes}}, as one can change tag patterns. | {{no}} | {{no}} | {{no}} | {{no}} |- ! {{verth|va=middle|ember}} | {{yes}} | {{yes}} | {{yes}} | {{no}} | {{yes}}, <syntaxhighlight lang="erb" inline><%xy%></syntaxhighlight> can be written as <code>%xy</code>. |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 <syntaxhighlight lang="erb" inline><%+ %></syntaxhighlight> but file contents are simply rendered into the output. |Treats the enclosed code as a block of Ruby code and (if necessary) appends a <code>do</code> keyword to the body of the tag. |}

== See also == {{Portal|Free and open-source software}} * mod_ruby * Phusion Passenger (''mod_rails'') * Haml * RDoc * Markaby

== References == <references />

== External links == * [https://docs.ruby-lang.org/en/master/ERB.html ERB Library] * [http://ruby-doc.com/docs/ProgrammingRuby/html/web.html "Ruby and the web"], a chapter from [http://ruby-doc.com/docs/ProgrammingRuby/ "The Pragmatic Programmer's Guide"] * [http://web-mode.org "web-mode.el"], emacs major mode for editing eRuby templates * [http://apidock.com/ruby/ERB ERB – Ruby Templating] * [https://docs.ruby-lang.org/en/master/ERB.html erb documentation] * [https://docs.ruby-lang.org/en/master/standard_library_md.html Ruby standard library] * [http://www.kuwata-lab.com/erubis/users-guide.html erubis documentation] {{Webarchive|url=https://web.archive.org/web/20170327220927/http://www.kuwata-lab.com/erubis/users-guide.html |date=2017-03-27 }} * [http://snk.tuxfamily.org/lib/ember/ ember documentation]

{{Ruby programming language}}

Category:Free computer libraries Category:Ruby (programming language) Category:Template engines