class ERB


The Ruby Toolbox.
of
Other popular engines could be found in the corresponding
can be reused elsewhere.
For example, RDoc, distributed with Ruby, uses its own template engine, which
There are a variety of templating solutions available in various Ruby projects.
== Notes
</html>
</body>
</p>
Call for a price, today!
<p>
</ul>
<li>Gem studded eyes… Rubies, of course!</li>
<li>Matz signature on left leg.</li>
<li>Karate-Chop Action!!!</li>
<li>Ignores Perl, Java, and all C variants.</li>
<li>Listens for verbal commands in the Ruby language!</li>
<ul>
<p>Geek’s Best Friend! Responds to Ruby commands…</p>
<h1>Rubysapien (TZ-1002)</h1>
<body>
<head><title>Ruby Toys – Rubysapien</title></head>
<html>
Generates (some blank lines removed):
rhtml.run(toy.get_binding)
# Produce result.
toy.add_feature(“Gem studded eyes… Rubies, of course!”)
toy.add_feature(“Matz signature on left leg.”)
toy.add_feature(“Karate-Chop Action!!!”)
toy.add_feature(“Ignores Perl, Java, and all C variants.”)
toy.add_feature(“Listens for verbal commands in the Ruby language!”)
999.95 )
“Geek’s Best Friend! Responds to Ruby commands…”,
“Rubysapien”,
toy = Product.new( “TZ-1002”,
# Set up template data.
rhtml = ERB.new(template)
}.gsub(/^ /, ”)
</html>
</body>
</p>
<% end %>
Call for a price, today!
<% else %>
Only <%= @cost %>!!!
<% if @cost < 10 %>
<p>
</ul>
<% end %>
<li><%= f %></li>
<% @features.each do |f| %>
<ul>
<p><%= @desc %></p>
<h1><%= @name %> (<%= @code %>)</h1>
<body>
<head><title>Ruby Toys – <%= @name %></title></head>
<html>
template = %{
# Create template.
end
# …
end
binding
def get_binding
# Support templating of member data.
end
@features << feature
def add_feature( feature )
end
@features = [ ]
@cost = cost
@desc = desc
@name = name
@code = code
def initialize( code, name, desc, cost )
class Product
# Build template data class.
require “erb”
variables in the Product object can be resolved.
this example to provide a special binding when the template is run, so that the instance
ERB is often used in .rhtml files (HTML with embedded Ruby). Notice the need in
=== Ruby in HTML
James Edward Gray II
Thanks for your patience.
* Answer Questions on Ruby Talk
* Document Modules
* Run Ruby Quiz
I want you to know that my team will keep working on the issues, especially:
Just wanted to send a quick note assuring that your needs are being addressed.
Community:
Subject: Addressing Needs
To: Community Spokesman <spokesman@ruby_community.org>
From: James Edward Gray II <james@grayproductions.net>
Generates:
puts email
email = message.result
# Produce result.
“Answer Questions on Ruby Talk” ]
“Document Modules”,
priorities = [ “Run Ruby Quiz”,
to = “Community Spokesman <spokesman@ruby_community.org>”
# Set up template data.
message = ERB.new(template, trim_mode: “%<>”)
}.gsub(/^ /, ”)
James Edward Gray II
Thanks for your patience.
% end
* <%= priority %>
% priorities.each do |priority|
<%# ignore numerous minor requests – focus on priorities %>
especially:
I want you to know that my team will keep working on the issues,
addressed.
Just wanted to send a quick note assuring that your needs are being
<%= to %>:
Subject: Addressing Needs
To: <%= to %>
From: James Edward Gray II <james@grayproductions.net>
template = %q{
# Create template.
require “erb”
%q{...} to avoid trouble with the backslash.
convenient “% at start of line” tag, and we quote the template literally with
ERB is useful for any generic templating situation. Note that in this example, we use the
=== Plain Text
== Examples
Prints: _ENCODING_ is Big5.
puts template.result
EOF
_ENCODING_ is <%= _ENCODING_ %>.
<%#-*- coding: Big5 -*-%>
template = ERB.new <<EOF
require ‘erb’
# -*- coding: utf-8 -*-
by the magic comment.
a magic comment, however, it returns a string in the encoding specified
character encoding as the input string. When the input string has
ERB (or Ruby code generated by ERB) returns a string in the same
== Character encodings
See the ERB.new and ERB#result methods for more detail.
* the binding used to resolve local variables in the template.
* the nature of the tags that are recognized;
There are several settings you can change when you use ERB:
== Options
All other text is passed through ERB filtering unchanged.
<%% or %%> – replace with <% or %> respectively
%% replaced with % if first thing on a line and % processing is used
% a line of Ruby code – treated as <% line %> (optional – see ERB.new)
<%# comment – ignored – useful in testing %> (‘<% #` doesn’t work. Don’t use Ruby comments.)
<%= Ruby expression – replace with result %>
<% Ruby code – inline with output %>
on the rules below:
ERB recognizes certain tags in the provided template and converts them based
== Recognized Tags
More complex examples are given below.
Prints: The value of x is: 42
puts template.result(binding)
EOF
The value of x is: <%= x %>
template = ERB.new <<-EOF
x = 42
require ‘erb’
A very simple example is this:
purposes of generating document information details and/or flow control.
ERB, actual Ruby code can be added to any plain text document for the
ERB provides an easy to use but powerful templating system for Ruby. Using
== Introduction
= ERB – Ruby Templating

def self.version

Returns revision information for the erb.rb module.
def self.version
  VERSION
end

def def_class(superklass=Object, methodname='result')

print MyClass.new('foo', 123).render()
MyClass = erb.def_class(MyClass_, 'render()')
erb.filename = filename
erb = ERB.new(File.read(filename))
filename = 'example.rhtml' # @arg1 and @arg2 are used in example.rhtml
end
end
@arg1 = arg1; @arg2 = arg2
def initialize(arg1, arg2)
class MyClass_
example:

Define unnamed class which has _methodname_ as instance method, and return it.
def def_class(superklass=Object, methodname='result')
  cls = Class.new(superklass)
  def_method(cls, methodname, @filename || '(ERB)')
  cls
end

def def_method(mod, methodname, fname='(ERB)')

print MyClass.new.render('foo', 123)
erb.def_method(MyClass, 'render(arg1, arg2)', filename)
erb = ERB.new(File.read(filename))
filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
example:

Define _methodname_ as instance method of _mod_ from compiled Ruby source.
def def_method(mod, methodname, fname='(ERB)')
  src = self.src.sub(/^(?!#|$)/) {"def #{methodname}\n"} << "\nend\n"
  mod.module_eval do
    eval(src, binding, fname, -1)
  end
end

def def_module(methodname='erb')

end
include MyModule
class MyClass
MyModule = erb.def_module('render(arg1, arg2)')
erb.filename = filename
erb = ERB.new(File.read(filename))
filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
example:

Create unnamed module, define _methodname_ as instance method of it, and return it.
def def_module(methodname='erb')
  mod = Module.new
  def_method(mod, methodname, @filename || '(ERB)')
  mod
end

def initialize(str, safe_level=NOT_GIVEN, legacy_trim_mode=NOT_GIVEN, legacy_eoutvar=NOT_GIVEN, trim_mode: nil, eoutvar: '_erbout')


A well massaged pattie, breaded and fried.
Chicken Fried Steak -- 9.95

A well massaged pattie, breaded and fried.
Chicken Fried Steak

_Generates_

puts listings.product + "\n" + listings.price

listings.build
listings = Listings.new
# setup template data

end
end
END_PRICE
<%= PRODUCT[:desc] %>
<%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
ERB.new(<<~'END_PRICE', trim_mode: "", eoutvar: "@price").result b
END_PRODUCT
<%= PRODUCT[:desc] %>
<%= PRODUCT[:name] %>
ERB.new(<<~'END_PRODUCT', trim_mode: "", eoutvar: "@product").result b
# create and run templates, filling member data variables
b = binding
def build

end
@price = price
@product = product
def initialize( product = "", price = "" )

attr_reader :product, :price

:cost => 9.95 }
:desc => "A well messaged pattie, breaded and fried.",
PRODUCT = { :name => "Chicken Fried Steak",
class Listings
# build data class

require "erb"

=== Example

output ends up. Pass the name of the variable to be used inside a String.
templates through the same binding and/or when you want to control where
its output in. This is useful when you need to run multiple ERB
_eoutvar_ can be used to set the name of the variable ERB will build up

- omit blank lines ending in -%>
> omit newline for lines ending in %>
<> omit newline for lines starting with <% and ending in %>
% enables Ruby code processing for lines beginning with %

modifiers, ERB will adjust its code generation as listed:
If _trim_mode_ is passed a String containing one or more of the following

the completed template when run.
An ERB object works by building a chunk of Ruby code that will output

Constructs a new ERB object with the template specified in _str_.
def initialize(str, safe_level=NOT_GIVEN, legacy_trim_mode=NOT_GIVEN, legacy_eoutvar=NOT_GIVEN, trim_mode: nil, eoutvar: '_erbout')
  # Complex initializer for $SAFE deprecation at [Feature #14256]. Use keyword arguments to pass trim_mode or eoutvar.
  if safe_level != NOT_GIVEN
    warn 'Passing safe_level with the 2nd argument of ERB.new is deprecated. Do not use it, and specify other arguments as keyword arguments.', uplevel: 1
  end
  if legacy_trim_mode != NOT_GIVEN
    warn 'Passing trim_mode with the 3rd argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, trim_mode: ...) instead.', uplevel: 1
    trim_mode = legacy_trim_mode
  end
  if legacy_eoutvar != NOT_GIVEN
    warn 'Passing eoutvar with the 4th argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, eoutvar: ...) instead.', uplevel: 1
    eoutvar = legacy_eoutvar
  end
  compiler = make_compiler(trim_mode)
  set_eoutvar(compiler, eoutvar)
  @src, @encoding, @frozen_string = *compiler.compile(str)
  @filename = nil
  @lineno = 0
  @_init = self.class.singleton_class
end

def location=((filename, lineno))


# from file.erb:4
# undefined local variable or method `some_x'
erb.render
# All subsequent error reporting would use new location
erb.location = ['file.erb', 3]

# from (erb):1
# undefined local variable or method `some_x'
erb.render
erb = ERB.new('<%= some_x %>')

evaluation and error reporting. See also #filename= and #lineno=
Sets optional filename and line number that will be used in ERB code
def location=((filename, lineno))
  @filename = filename
  @lineno = lineno if lineno
end

def make_compiler(trim_mode)

def make_compiler(trim_mode)
  ERB::Compiler.new(trim_mode)
end

def new_toplevel(vars = nil)

def new_toplevel(vars = nil)
  b = TOPLEVEL_BINDING
  if vars
    vars = vars.select {|v| b.local_variable_defined?(v)}
    unless vars.empty?
      return b.eval("tap {|;#{vars.join(',')}| break binding}")
    end
  end
  b.dup
end

def result(b=new_toplevel)


code evaluation.
_b_ accepts a Binding object which is used to set the context of

the results of that code.
Executes the generated ERB code to produce a completed template, returning
def result(b=new_toplevel)
  unless @_init.equal?(self.class.singleton_class)
    raise ArgumentError, "not initialized"
  end
  eval(@src, b, (@filename || '(erb)'), @lineno)
end

def result_with_hash(hash)

by a Hash object.
Render a template on a new toplevel binding with local variables specified
def result_with_hash(hash)
  b = new_toplevel(hash.keys)
  hash.each_pair do |key, value|
    b.local_variable_set(key, value)
  end
  result(b)
end

def run(b=new_toplevel)

Generate results and print them. (see ERB#result)
def run(b=new_toplevel)
  print self.result(b)
end

def set_eoutvar(compiler, eoutvar = '_erbout')


requires the setup of an ERB _compiler_ object.
easier to just use the constructor though, since calling this method
Can be used to set _eoutvar_ as described in ERB::new. It's probably
def set_eoutvar(compiler, eoutvar = '_erbout')
  compiler.put_cmd = "#{eoutvar}.<<"
  compiler.insert_cmd = "#{eoutvar}.<<"
  compiler.pre_cmd = ["#{eoutvar} = +''"]
  compiler.post_cmd = [eoutvar]
end