Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
285 changes: 64 additions & 221 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,255 +1,98 @@
# ERB
# \ERB (Embedded Ruby)

An easy to use but powerful templating system for Ruby.
\ERB is an easy-to-use, but also very powerful, [template processor][template processor].

## Introduction
\ERB is commonly used to produce:

ERB provides an easy to use but powerful templating system for Ruby. Using
ERB, actual Ruby code can be added to any plain text document for the
purposes of generating document information details and/or flow control.
- Customized or personalized email messages.
- Customized or personalized web pages.
- Software code (in code-generating applications).

A very simple example is this:
Like method [sprintf][sprintf], \ERB can format run-time data into a string.
\ERB, however, is *much more powerful*

```rb
require 'erb'
## How \ERB Works

x = 42
template = ERB.new <<-EOF
The value of x is: <%= x %>
EOF
puts template.result(binding)
```
Using \ERB, you can create a *template*: a plain-text string that has specially-formatted *tags*,
then store it into an \ERB object;
when \ERB produces _result_ string, it:

Prints: `The value of x is: 42`
- Inserts run-time-evaluated expressions into the result.
- Executes snippets of Ruby code.
- Omits comments from the results.

More complex examples are given below.
In the result:

## Recognized Tags
- All non-tag text is passed through, _unchanged_.
- Each tag is either _replaced_ (expression tag),
or _omitted_ entirely (execution tag or comment tag).

ERB recognizes certain tags in the provided template and converts them based
on the rules below:
There are three types of tags:

```erb
<% Ruby code -- inline with output %>
<%= Ruby expression -- replace with result %>
<%# comment -- ignored -- useful in testing %> (`<% #` doesn't work. Don't use Ruby comments.)
% a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
%% replaced with % if first thing on a line and % processing is used
<%% or %%> -- replace with <% or %> respectively
```
| Tag | Form | Action | Text in Result |
|----------------|:------------------------------------:|:-------------------------------------:|:--------------------:|
| Expression tag | <tt>'<%= _ruby_expression_ %>'</tt> | Evaluates <tt>_ruby_expression_</tt>. | Value of expression. |
| Execution tag | <tt>'<% _ruby_code_ %>'</tt> | Execute <tt>_ruby_code_</tt>. | None. |
| Comment tag | <tt>'<%# _comment_text_ %>'</tt> | None. | None. |

All other text is passed through ERB filtering unchanged.
These examples use `erb`, the \ERB command-line interface;
each "echoes" a string template and pipes it to `erb` as input:

## Options

There are several settings you can change when you use ERB:
* the nature of the tags that are recognized;
* the binding used to resolve local variables in the template.
- Expression tag:

See the ERB.new and ERB#result methods for more detail.
$ echo "<%= $VERBOSE %>" | erb
"false"
$ echo "<%= 2 + 2 %>" | erb
"4"

## Character encodings
- Execution tag:

ERB (or Ruby code generated by ERB) returns a string in the same
character encoding as the input string. When the input string has
a magic comment, however, it returns a string in the encoding specified
by the magic comment.
echo "<% if $VERBOSE %> Long message. <% else %> Short message. <% end %>" | erb
" Short message. "

```rb
# -*- coding: utf-8 -*-
require 'erb'
- Comment tag:

template = ERB.new <<EOF
<%#-*- coding: Big5 -*-%>
__ENCODING__ is <%= __ENCODING__ %>.
EOF
puts template.result
```
echo "<%# TODO: Fix this nonsense. %> Nonsense." | erb
" Nonsense."

Prints: `__ENCODING__ is Big5.`
## How to Use \ERB

## Examples
You can use \ERB either:

### Plain Text
- In a program: see class ERB.
- From the command line: see [ERB Executable][erb executable].

ERB is useful for any generic templating situation. Note that in this example, we use the
convenient "% at start of line" tag, and we quote the template literally with
`%q{...}` to avoid trouble with the backslash.
## Installation

```rb
require "erb"
\ERB is installed with Ruby, and so there's no further installation needed.

# Create template.
template = %q{
From: James Edward Gray II <james@grayproductions.net>
To: <%= to %>
Subject: Addressing Needs
## Other Template Engines

<%= to[/\w+/] %>:

Just wanted to send a quick note assuring that your needs are being
addressed.

I want you to know that my team will keep working on the issues,
especially:

<%# ignore numerous minor requests -- focus on priorities %>
% priorities.each do |priority|
* <%= priority %>
% end

Thanks for your patience.

James Edward Gray II
}.gsub(/^ /, '')

message = ERB.new(template, trim_mode: "%<>")

# Set up template data.
to = "Community Spokesman <spokesman@ruby_community.org>"
priorities = [ "Run Ruby Quiz",
"Document Modules",
"Answer Questions on Ruby Talk" ]

# Produce result.
email = message.result
puts email
```

Generates:

```
From: James Edward Gray II <james@grayproductions.net>
To: Community Spokesman <spokesman@ruby_community.org>
Subject: Addressing Needs

Community:

Just wanted to send a quick note assuring that your needs are being addressed.

I want you to know that my team will keep working on the issues, especially:

* Run Ruby Quiz
* Document Modules
* Answer Questions on Ruby Talk

Thanks for your patience.

James Edward Gray II
```

### Ruby in HTML

ERB is often used in .rhtml files (HTML with embedded Ruby). Notice the need in
this example to provide a special binding when the template is run, so that the instance
variables in the Product object can be resolved.

```rb
require "erb"

# Build template data class.
class Product
def initialize( code, name, desc, cost )
@code = code
@name = name
@desc = desc
@cost = cost

@features = [ ]
end

def add_feature( feature )
@features << feature
end

# Support templating of member data.
def get_binding
binding
end

# ...
end

# Create template.
template = %{
<html>
<head><title>Ruby Toys -- <%= @name %></title></head>
<body>

<h1><%= @name %> (<%= @code %>)</h1>
<p><%= @desc %></p>

<ul>
<% @features.each do |f| %>
<li><b><%= f %></b></li>
<% end %>
</ul>

<p>
<% if @cost < 10 %>
<b>Only <%= @cost %>!!!</b>
<% else %>
Call for a price, today!
<% end %>
</p>

</body>
</html>
}.gsub(/^ /, '')

rhtml = ERB.new(template)
There are a variety of template engines available in various Ruby projects.
For example, [RDoc][rdoc], distributed with Ruby, uses its own template engine, which
can be reused elsewhere.

# Set up template data.
toy = Product.new( "TZ-1002",
"Rubysapien",
"Geek's Best Friend! Responds to Ruby commands...",
999.95 )
toy.add_feature("Listens for verbal commands in the Ruby language!")
toy.add_feature("Ignores Perl, Java, and all C variants.")
toy.add_feature("Karate-Chop Action!!!")
toy.add_feature("Matz signature on left leg.")
toy.add_feature("Gem studded eyes... Rubies, of course!")
Other popular template engines may be found in the [Ruby Toolbox][ruby toolbox].

# Produce result.
rhtml.run(toy.get_binding)
```
## Code

Generates (some blank lines removed):
The \ERB source code is in GitHub project [ruby/erb][ruby/erb]/

```html
<html>
<head><title>Ruby Toys -- Rubysapien</title></head>
<body>

<h1>Rubysapien (TZ-1002)</h1>
<p>Geek's Best Friend! Responds to Ruby commands...</p>

<ul>
<li><b>Listens for verbal commands in the Ruby language!</b></li>
<li><b>Ignores Perl, Java, and all C variants.</b></li>
<li><b>Karate-Chop Action!!!</b></li>
<li><b>Matz signature on left leg.</b></li>
<li><b>Gem studded eyes... Rubies, of course!</b></li>
</ul>

<p>
Call for a price, today!
</p>

</body>
</html>
```

## Notes

There are a variety of templating solutions available in various Ruby projects.
For example, RDoc, distributed with Ruby, uses its own template engine, which
can be reused elsewhere.
## Bugs

Other popular engines could be found in the corresponding
[Category](https://www.ruby-toolbox.com/categories/template_engines) of
The Ruby Toolbox.
Bugs may be reported at [ERB Issues][erb issues].

## License

The gem is available as open source under the terms of the [2-Clause BSD License](https://opensource.org/licenses/BSD-2-Clause).
This software is available as open source under the terms
of the [2-Clause BSD License][2-clause bsd license].

[2-clause bsd license]: https://opensource.org/licenses/BSD-2-Clause
[erb executable]: rdoc-ref:erb_executable.md
[erb issues]: https://github.com/ruby/erb/issues
[rdoc]: https://ruby.github.io/rdoc/
[ruby/erb]: https://github.com/ruby/erb
[ruby toolbox]: https://www.ruby-toolbox.com/categories/template_engines
[sprintf]: https://docs.ruby-lang.org/en/master/Kernel.html#method-i-sprintf
[template processor]: https://en.wikipedia.org/wiki/Template_processor_
Loading