Erubis Users' Guide

last update: $Date: 2006-09-24 21:01:00 +0900 (Sun, 24 Sep 2006) $

Preface

Erubis is an implementation of eRuby. It has the following features.

Erubis is implemented in pure Ruby. It requires Ruby 1.8 or higher.

Table of Contents



Installation


Tutorial

Basic Example

Here is a basic example of Erubis.

example1.eruby
<ul>
  <% for item in list %>
  <li><%= item %></li>
  <% end %>
  <%# here is ignored because starting with '#' %>
</ul>
example1.rb
require 'erubis'
input = File.read('example1.eruby')
eruby = Erubis::Eruby.new(input)    # create Eruby object

puts "---------- script source ---"
puts eruby.src                      # print script source

puts "---------- result ----------"
list = ['aaa', 'bbb', 'ccc']
puts eruby.result(binding())        # get result

## # or
## eruby = Erubis::Eruby.new
## input = File.read('example1.eruby')
## src = eruby.convert(input)
## eval src
output
$ ruby example1.rb
---------- script source ---
_buf = []; _buf << '<ul>
';   for item in list 
 _buf << '  <li>'; _buf << ( item ).to_s; _buf << '</li>
';   end 

 _buf << '</ul>
';
_buf.join
---------- result ----------
<ul>
  <li>aaa</li>
  <li>bbb</li>
  <li>ccc</li>
</ul>

Erubis has command 'erubis'. Command-line option '-x' shows the compiled source code of eRuby script.

example of command-line option '-x'
$ erubis -x example1.eruby
_buf = []; _buf << '<ul>
';   for item in list 
 _buf << '  <li>'; _buf << ( item ).to_s; _buf << '</li>
';   end 

 _buf << '</ul>
';
_buf.join

Trimming Spaces

Erubis deletes spaces around '<% %>' automatically, while it leaves spaces around '<%= %>'.

example2.eruby
<ul>
  <% for item in list %>      # trimmed
  <li>
    <%= item %>               # not trimmed
  </li>
  <% end %>                   # trimmed
</ul>
compiled source code
$ erubis -x example2.eruby
_buf = []; _buf << '<ul>
';   for item in list 
 _buf << '  <li>
'; _buf << '    '; _buf << ( item ).to_s; _buf << '
'; _buf << '  </li>
';   end 
 _buf << '</ul>
';
_buf.join

If you want leave spaces around '<% %>', add command-line option '-T'.

compiled source code with command-line option '-T'
$ erubis -x -T example2.eruby
_buf = []; _buf << '<ul>
'; _buf << '  '; for item in list ; _buf << '
'; _buf << '  <li>
'; _buf << '    '; _buf << ( item ).to_s; _buf << '
'; _buf << '  </li>
'; _buf << '  '; end ; _buf << '
'; _buf << '</ul>
';
_buf.join

Or add option :trim=>false to Erubis::Eruby.new().

example2.rb
require 'erubis'
input = File.read('example2.eruby')
eruby = Erubis::Eruby.new(input, :trim=>false)

puts "---------- script source ---"
puts eruby.src                            # print script source

puts "---------- result ----------"
list = ['aaa', 'bbb', 'ccc']
puts eruby.result(binding())              # get result
output
$ ruby example2.rb
---------- script source ---
_buf = []; _buf << '<ul>
'; _buf << '  '; for item in list ; _buf << '
'; _buf << '  <li>
'; _buf << '    '; _buf << ( item ).to_s; _buf << '
'; _buf << '  </li>
'; _buf << '  '; end ; _buf << '
'; _buf << '</ul>
';
_buf.join
---------- result ----------
<ul>
  
  <li>
    aaa
  </li>
  
  <li>
    bbb
  </li>
  
  <li>
    ccc
  </li>
  
</ul>

Escape

Erubis have ability to escape (sanitize) expression. Erubis::Eruby class act as the following:

Erubis::EscapedEruby(*1) class handle '<%= %>' as escaped and '<%== %>' as not escaped. It means that using Erubis::EscapedEruby you can escape expression by default. Also Erubis::XmlEruby class (which is equivalent to Erubis::EscapedEruby) is provided for compatibility with Erubis 1.1.

example3.eruby
<% for item in list %>
  <p><%= item %></p>
  <p><%== item %></p>
  <p><%=== item %></p>

<% end %>
example3.rb
require 'erubis'
input = File.read('example3.eruby')
eruby = Erubis::EscapedEruby.new(input)    # or Erubis::XmlEruby

puts "---------- script source ---"
puts eruby.src                             # print script source

puts "---------- result ----------"
list = ['<aaa>', 'b&b', '"ccc"']
puts eruby.result(binding())               # get result
output
$ ruby example3.rb 2> stderr.log
---------- script source ---
_buf = []; for item in list 
 _buf << '  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; $stderr.puts("*** debug: item=#{(item).inspect}"); _buf << '</p>

'; end 
_buf.join
---------- result ----------
  <p>&lt;aaa&gt;</p>
  <p><aaa></p>
  <p></p>

  <p>b&amp;b</p>
  <p>b&b</p>
  <p></p>

  <p>&quot;ccc&quot;</p>
  <p>"ccc"</p>
  <p></p>

$ cat stderr.log
*** debug: item="<aaa>"
*** debug: item="b&b"
*** debug: item="\"ccc\""

The command-line option '-e' will do the same action as Erubis::EscapedEruby. This option is available for any language.

$ erubis -l ruby -e example3.eruby
_buf = []; for item in list 
 _buf << '  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; $stderr.puts("*** debug: item=#{(item).inspect}"); _buf << '</p>

'; end 
_buf.join

Escaping function (default 'Erubis::XmlHelper.escape_xml()') can be changed by command-line property '--escapefunc=xxx' or by overriding Erubis::Eruby#escaped_expr() in subclass.

example to override Erubis::Eruby#escaped_expr()
class CGIEruby < Erubis::Eruby
  def escaped_expr(code)
    return "CGI.escapeHTML((#{code.strip}).to_s)"
    #return "h(#{code.strip})"
  end
end

class LatexEruby < Erubi::Eruby
  def escaped_expr(code)
    return "(#{code}).gsub(/[%\\]/,'\\\\\&')"
  end
end
(*1)
Erubis::EscapedEruby class includes Erubis::EscapeEnhancer which swtches the action of '<%= %>' and '<%== %>'.

Embedded Pattern

You can change embedded pattern '<% %>' to another by command-line option '-p' or option ':pattern=>...' of Erubis::Eruby.new().

example4.eruby
<!--% for item in list %-->
  <p><!--%= item %--></p>
<!--% end %-->
compiled source code with command-line option '-p'
$ erubis -x -p '<!--% %-->' example4.eruby
_buf = []; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
'; end 
_buf.join
example4.rb
require 'erubis'
input = File.read('example4.eruby')
eruby = Erubis::Eruby.new(input, :pattern=>'<!--% %-->')
                                      # or '<(?:!--)?% %(?:--)?>'

puts "---------- script source ---"
puts eruby.src                            # print script source

puts "---------- result ----------"
list = ['aaa', 'bbb', 'ccc']
puts eruby.result(binding())              # get result
output
$ ruby example4.rb
---------- script source ---
_buf = []; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
'; end 
_buf.join
---------- result ----------
  <p>aaa</p>
  <p>bbb</p>
  <p>ccc</p>

It is able to specify regular expression with :pattern option. Notice that you must use '(?: )' instead of '( )' for grouping. For example, '<(!--)?% %(--)?>' will not work while '<(?:!--)?% %(?:--)?>' will work.


Context Object

Context object is a set of data which are used in eRuby script. Using context object makes clear which data to be used. In Erubis, Hash object and Erubis::Context object are available as context object.

Context data can be accessible via isntance variables in eRuby script.

example5.eruby
<span><%= @val %></span>
<ul>
 <% for item in @list %>
  <li><%= item %></li>
 <% end %>
</ul>
example5.rb
require 'erubis'
input = File.read('example5.eruby')
eruby = Erubis::Eruby.new(input)      # create Eruby object

## create context object
## (key means var name, which may be string or symbol.)
context = {
  :val   => 'Erubis Example',
  'list' => ['aaa', 'bbb', 'ccc'],
}
  # or
  #   context = Erubis::Context.new()
  #   context['val'] = 'Erubis Example'
  #   context[:list] = ['aaa', 'bbb', 'ccc'],

puts eruby.evaluate(context)         # get result
output
$ ruby example5.rb
<span>Erubis Example</span>
<ul>
  <li>aaa</li>
  <li>bbb</li>
  <li>ccc</li>
</ul>

The difference between Erubis#result(binding) and Erubis#evaluate(context) is that the former invokes 'eval @src, binding' and the latter invokes 'context.instance_eval @src'. This means that data is passed into eRuby script via local variable when Eruby::binding() is called, or instance variable when Eruby::evaluate() is called.

Here is the definition of Erubis#result() and Erubis#evaluate().

definition of result(binding) and evaluate(context)
def result(_binding)
  if _binding.is_a?(Hash)
    # load hash data as local variable
    _h = _binding
    eval _h.keys.inject("") {|s,k| s << "#{k} = _h[#{k.inspect}];"}
    _binding = binding()
  end
  return eval(@src, _binding)
end

def evaluate(context)
  if context.is_a?(Hash)
    # convert hash object to Context object
    hash = context
    context = Erubis::Context.new
    hash.each { |key, val| context[key] = val }
  end
  return context.instance_eval(@src)
end

instance_eval() is defined at Object class so it is able to use any object as a context object as well as Hash or Erubis::Context.

example6.rb
class MyData
  attr_accessor :val, :list
end

## any object can be a context object
mydata = MyData.new
mydata.val = 'Erubis Example'
mydata.list = ['aaa', 'bbb', 'ccc']

require 'erubis'
eruby = Erubis::Eruby.new(File.read('example5.eruby'))
puts eruby.evaluate(mydata)
output
$ ruby example6.rb
<span>Erubis Example</span>
<ul>
  <li>aaa</li>
  <li>bbb</li>
  <li>ccc</li>
</ul>

Context Data File

It is very useful to import YAML document data into Hash context object.

example7.yaml
title: Users List
users:
  - name:  foo
    mail:  foo@mail.com
  - name:  bar
    mail:  bar@mail.net
  - name:  baz
    mail:  baz@mail.org
example7.eruby
<h1><%= @title %></h1>
<ul>
 <% for user in @users %>
  <li>
    <a href="mailto:<%= user['mail']%>"><%= user['name'] %></a>
  </li>
 <% end %>
</ul>
example7.rb
require 'erubis'
input = File.read('example7.eruby')
eruby = Erubis::Eruby.new(input)      # create Eruby object

## load YAML document as context object
require 'yaml'
context = YAML.load_file('example7.yaml')

puts eruby.evaluate(context)        # get result
output
$ ruby example7.rb
<h1>Users List</h1>
<ul>
  <li>
    <a href="mailto:foo@mail.com">foo</a>
  </li>
  <li>
    <a href="mailto:bar@mail.net">bar</a>
  </li>
  <li>
    <a href="mailto:baz@mail.org">baz</a>
  </li>
</ul>

It is able to specify YAML data file with the command-line option '-f'. You don't have to write ruby script such as 'example7.rb'.

example of command-line option '-f'
$ erubis -f example7.yaml example7.eruby
<h1>Users List</h1>
<ul>
  <li>
    <a href="mailto:foo@mail.com">foo</a>
  </li>
  <li>
    <a href="mailto:bar@mail.net">bar</a>
  </li>
  <li>
    <a href="mailto:baz@mail.org">baz</a>
  </li>
</ul>

Command-line option '-S' converts keys of mapping in YAML data file from string into symbol. Command-line option '-B' invokes 'Erubis::Eruby#result(binding())' instead of 'Erubis::Eruby#evaluate(context)'.


Preamble and Postamble

The first line ('_buf = [];') in the compiled source code is called preamble and the last line ('_buf.join') is called postamble.

Command-line option '-b' skips the output of preamble and postamble.

example8.eruby
<% for item in @list %>
 <b><%= item %></b>
<% end %>

compiled source code with and without command-line option '-b'

## without '-b'
$ erubis -x example8.eruby
_buf = []; for item in @list 
 _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end 
_buf.join

## with '-b'
$ erubis -x -b example8.eruby
 for item in @list 
 _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end 

Erubis::Eruby.new option ':preamble=>false' and ':postamble=>false' also suppress output of preamble or postamle.

example8.rb
require 'erubis'
input = File.read('example8.eruby')
eruby1 = Erubis::Eruby.new(input)
eruby2 = Erubis::Eruby.new(input, :preamble=>false, :postamble=>false)

puts eruby1.src   # print preamble and postamble
puts "--------------"
puts eruby2.src   # don't print preamble and postamble
output
$ ruby example8.rb
_buf = []; for item in @list 
 _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end 
_buf.join
--------------
 for item in @list 
 _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end 

Processing Instruction (PI) Converter

Erubis can parse Processing Instructions (PI) as embedded pattern.

This is more useful than basic embedded pattern ('<% ... >') because PI doesn't break XML or HTML at all. For example the following XHTML file is well-formed and HTML validator got no errors on this example.

example9.xhtml
<?xml version="1.0" ?>
<?rb
  lang = 'en'
  list = ['<aaa>', 'b&b', '"ccc"']
?>
<html lang="@!{lang}@">
 <body>
  <ul>
  <?rb for item in list ?>
   <li>@{item}@</li>
  <?rb end ?>
  </ul>
 </body>
</html>

If the command-line property '--pi=name' is specified, erubis command parses input with PI converter. If name is omitted then the following name is used according to '-l lang'.

mapping of '-l' option and PI name
'-l' option PI name
-l ruby <?rb ... ?>
-l php <?php ... ?>
-l perl <?perl ... ?>
-l java <?java ... ?>
-l javascript <?js ... ?>
-l scheme <?scheme ... ?>
output
$ erubis --pi example9.xhtml
<?xml version="1.0" ?>
<html lang="en">
 <body>
  <ul>
   <li>&lt;aaa&gt;</li>
   <li>b&amp;b</li>
   <li>&quot;ccc&quot;</li>
  </ul>
 </body>
</html>

Expression character can be changeable by command-line property '--embchar=char. Default is '@'.

(experimental) Erubis supports '<%= ... %>' pattern with PI pattern.

example of Rails view template
<table>
  <tr>
<?rb for item in @list ?>
    <td>@{item.id}@</td>
    <td>@{item.name}@</td>
    <td>
       <%= link_to 'Destroy', {:action=>'destroy', :id=>item.id},
                       :confirm=>'Are you OK?' %>
    </td>
<?rb end ?>
  </tr>
</table>


Enhancer

Enhancer is a module to add a certain feature into Erubis::Eruby class. Enhancer may be language-independent or only for Erubis::Eruby class.

To use enhancers, define subclass and include them. The folloing is an example to use EscapeEnhancer, PercentLineEnhancer, and BiPatternEnhancer.

class MyEruby < Erubis::Eruby
  include EscapeEnhancer
  include PercentLineEnhancer
  include BiPatternEnhancer
end

You can specify enhancers in command-line with option '-E'. The following is an example to use some enhancers in command-line.

$ erubis -xE Escape,PercentLine,BiPattern example.eruby

The following is the list of enhancers.

EscapeEnhander (language-independent)
Switch '<%= %>' to escaped and '<%== %>' to unescaped.
StdoutEnhancer (only for Eruby)
Use $stdout instead of array buffer.
PrintOutEnhancer (only for Eruby)
Use "print(...)" statement insead of "_buf << ...".
PrintEnabledEnhancer (only for Eruby)
Enable to use print() in '<% ... %>'.
ArrayEnhancer (only for Eruby)
Return array of string instead of returning string.
ArrayBufferEnhancer (only for Eruby)
Use array buffer. This is included in Erubis::Eruby by default.
StringBufferEnhancer (only for Eruby)
Use string buffer. It is a little slower than ArrayBufferEnhancer.
NoTextEnhancer (language-independent)
Print embedded code only and ignore normal text.
NoCodeEnhancer (language-independent)
Print normal text only and ignore code.
SimplifyEnhancer (language-independent)
Make compile faster but don't trim spaces around '<% %>'.
BiPatternEnhancer (language-independent)
[experimental] Enable to use another embedded pattern with '<% %>'.
PercentLineEnhancer (language-independent)
Regard lines starting with '%' as Ruby code. This is for compatibility with eruby and ERB.
HeaderFooterEnhancer (language-independent)
[experimental] Enable you to add header and footer in eRuby script.

If you required 'erubis/engine/enhanced', Eruby subclasses which include each enhancers are defined. For example, class BiPatternEruby includes BiPatternEnhancer.

EscapeEnhancer

EscapeEnhancer switches '<%= ... %>' to escaped and '<%== ... %>' to unescaped.

example.eruby
<div>
<% for item in list %>
  <p><%= item %></p>
  <p><%== item %></p>
<% end %>
</div>
compiled source code
$ erubis -xE Escape example.eruby
_buf = []; _buf << '<div>
'; for item in list 
 _buf << '  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
  <p>'; _buf << ( item ).to_s; _buf << '</p>
'; end 
 _buf << '</div>
';
_buf.join

EscapeEnhancer is language-independent.


StdoutEnhancer

StdoutEnhancer use $sdtdout instead of array buffer. Therefore, you can use 'print' statement in embedded ruby code.

compiled source code
$ erubis -xE Stdout example.eruby
_buf = $stdout; _buf << '<div>
'; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end 
 _buf << '</div>
';
''

StdoutEnhancer is only for Eruby.


PrintOutEnhancer

PrintOutEnhancer makes compiled source code to use 'print(...)' instead of '_buf << ...'.

compiled source code
$ erubis -xE PrintOut example.eruby
 print '<div>
'; for item in list 
 print '  <p>'; print(( item ).to_s); print '</p>
  <p>'; print Erubis::XmlHelper.escape_xml( item ); print '</p>
'; end 
 print '</div>
';

PrintOutEnhancer is only for Eruby.


PrintEnabledEnhancer

PrintEnabledEnhancer enables you to use print() method in '<% ... %>'.

printenabled-example.eruby
<% for item in @list %>
  <b><% print item %></b>
<% end %>
printenabled-example.rb
require 'erubis'
class PrintEnabledEruby < Erubis::Eruby
  include Erubis::PrintEnabledEnhancer
end
input = File.read('printenabled-example.eruby')
eruby = PrintEnabledEruby.new(input)
list = ['aaa', 'bbb', 'ccc']
print eruby.evaluate(:list=>list)
output result
$ ruby printenabled-example.rb
  <b>aaa</b>
  <b>bbb</b>
  <b>ccc</b>

Notice to use Eruby#evaluate() and not to use Eruby#result(), because print() method in '<% ... %>' invokes not Kernel#print() but PrintEnabledEnhancer#print().

PrintEnabledEnhancer is only for Eruby.


ArrayEnhancer

ArrayEnhancer makes Eruby to return an array of strings.

compiled source code
_buf = []; _buf << '<div>
'; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end 
 _buf << '</div>
';
_buf

ArrayEnhancer is only for Eruby.


ArrayBufferEnhancer

Arraybufferenhancer makes Eruby to use array buffer. Array buffer is a litte faster than String buffer. Erubis::Eruby includes this enhancer by default.

ArrayBufferEnhancer is only for Eruby.


StringBufferEnhancer

StringBufferEnhancer makes Eruby to use string buffer.

$ erubis -xE StringBuffer example.eruby
_buf = ''; _buf << '<div>
'; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end 
 _buf << '</div>
';
_buf

StringBufferEnhancer is only for Eruby.


NoTextEnhancer

NoTextEnhancer suppress output of text and prints only embedded code. This is useful especially when debugging a complex eRuby script.

notext-example.eruby
<h3>List</h3>
<% if !@list || @list.empty? %>
<p>not found.</p>
<% else %>
<table>
  <tbody>
    <% @list.each_with_index do |item, i| %>
    <tr bgcolor="<%= i%2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
      <td><%= item %></td>
    </tr>
    <% end %>
  </tbody>
</table>
<% end %>
output example of NoTextEnhancer
$ erubis -TxE NoText notext-example.eruby
_buf = [];
 if !@list || @list.empty? ;

 else ;


     @list.each_with_index do |item, i| ;
                  _buf << ( i%2 == 0 ? '#FFCCCC' : '#CCCCFF' ).to_s;
           _buf << ( item ).to_s;

     end ;


 end ;
_buf.join

NoTextEnhancer is language-independent. It is useful even if you are PHP user, see this section.


NoCodeEnhancer

NoCodeEnhancer suppress output of embedded code and prints only normal text. This is useful especially when validating HTML tags.

nocode-example.eruby
<h3>List</h3>
<% if !@list || @list.empty? %>
<p>not found.</p>
<% else %>
<table>
  <tbody>
    <% @list.each_with_index do |item, i| %>
    <tr bgcolor="<%= i%2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
      <td><%= item %></td>
    </tr>
    <% end %>
  </tbody>
</table>
<% end %>
output example of NoTextEnhancer
$ erubis -TxE NoCode notext-example.eruby
<h3>List</h3>

<p>not found.</p>

<table>
  <tbody>
    
    <tr bgcolor="">
      <td></td>
    </tr>
    
  </tbody>
</table>

NoCodeEnhancer is language-independent. It is useful even if you are PHP user, see this section.


SimplifyEnhancer

SimplifyEnhancer makes compiling a little faster but don't trim spaces around '<% %>'.

compiled source code
$ erubis -xE Simplify example.euby
_buf = []; _buf << '<div>
'; for item in list ; _buf << '
  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end ; _buf << '
</div>
';
_buf.join

SimplifyEnhancer is language-independent.


BiPatternEnhancer

BiPatternEnhancer enables to use another embedded pattern with '<% %>'. By Default, '[= ... =]' is available for expression. You can specify pattern by :bipattern property.

bipattern-example.rhtml
<% for item in list %>
  <b>[= item =]</b>
  <b>[== item =]</b>
<% end %>
compiled source code
$ erubis -xE BiPattern bipattern-example.rhtml
_buf = []; for item in list 
 _buf << '  <b>'; _buf << ( item ).to_s; _buf << '</b>
  <b>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</b>
'; end 
_buf.join

BiPatternEnhancer is language-independent.


PercentLineEnhancer

PercentLineEnhancer regards lines starting with '%' as Ruby code. This is for compatibility with eruby and ERB.

percentline-example.rhtml
% for item in list
  <b><%= item %></b>
% end
%% lines with '%%'
compiled source code
$ erubis -xE PercentLine percentline-example.rhtml
_buf = []; for item in list
 _buf << '  <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end
 _buf << '% lines with \'%%\'
';
_buf.join

PercentLineEnhancer is language-independent.


HeaderFooterEnhancer

[experimental]

HeaderFooterEnhancer enables you to add header and footer in eRuby script.

headerfooter-example.eruby
<!--#header:
def list_items(items)
#-->
<% for item in items %>
  <b><%= item %></b>
<% end %>
<!--#footer:
end
#-->
compiled source code
$ erubis -xE HeaderFooter headerfooter-example.eruby

def list_items(items)

_buf = []; for item in items 
 _buf << '  <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end 
_buf.join

end

Compare to the following:

normal-eruby-test.eruby
<%
def list_items(items)
%>
<% for item in items %>
<li><%= item %></li>
<% end %>
<%
end
%>
compiled source code
$ erubis -x normal-eruby-test.eruby
_buf = [];
def list_items(items)

 for item in items 
 _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
'; end 

end

_buf.join

Header and footer can be in any position in eRuby script, that is, header is no need to be in the head of eRuby script.

headerfooter-example2.rhtml
<?xml version="1.0"?>
<html>
<!--#header:
def page(list)
#-->
 :
<!--#footer:
end
#-->
</html>
compiled source code
$ erubis -xE HeaderFooter headerfooter-example2.rhtml

def page(list)

_buf = []; _buf << '<?xml version="1.0"?>
<html>
'; _buf << ' :
'; _buf << '</html>
';
_buf.join

end

HeaderFooterEnhancer is experimental and is language-independent.



Multi-Language

Erubis supports the following language currently:

PHP

example.ephp
<?xml version="1.0"?>
<html>
 <body>
  <p>Hello <%= $user %>!</p>
  <table>
   <tbody>
    <% $i = 0; %>
    <% foreach ($list as $item) { %>
    <%   $i++; %>
    <tr bgcolor="<%= $i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
     <td><%= $i %></td>
     <td><%== $item %></td>
    </tr>
    <% } %>
   </tbody>
  </table>
 </body>
</html>
compiled source code
$ erubis -l php example.ephp
<<?php ?>?xml version="1.0"?>
<html>
 <body>
  <p>Hello <?php echo $user; ?>!</p>
  <table>
   <tbody>
<?php     $i = 0; ?>
<?php     foreach ($list as $item) { ?>
<?php       $i++; ?>
    <tr bgcolor="<?php echo $i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'; ?>">
     <td><?php echo $i; ?></td>
     <td><?php echo htmlspecialchars($item); ?></td>
    </tr>
<?php     } ?>
   </tbody>
  </table>
 </body>
</html>

C

example.ec
<%
#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

%>
<html>
 <body>
  <p>Hello <%= "%s", argv[0] %>!</p>
  <table>
   <tbody>
    <% for (i = 1; i < argc; i++) { %>
    <tr bgcolor="<%= i % 2 == 0 ? "#FFCCCC" : "#CCCCFF" %>">
      <td><%= "%d", i %></td>
      <td><%= "%s", argv[i] %></td>
    </tr>
    <% } %>
   </tbody>
  </table>
 </body>
</html>
<%
    return 0; 
}
%>
compiled source code
$ erubis -l c example.ec
#line 1 "example.ec"

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;


fputs("<html>\n"
      " <body>\n"
      "  <p>Hello ", stdout); fprintf(stdout, "%s", argv[0]); fputs("!</p>\n"
      "  <table>\n"
      "   <tbody>\n", stdout);
     for (i = 1; i < argc; i++) { 
fputs("    <tr bgcolor=\"", stdout); fprintf(stdout, i % 2 == 0 ? "#FFCCCC" : "#CCCCFF"); fputs("\">\n"
      "      <td>", stdout); fprintf(stdout, "%d", i); fputs("</td>\n"
      "      <td>", stdout); fprintf(stdout, "%s", argv[i]); fputs("</td>\n"
      "    </tr>\n", stdout);
     } 
fputs("   </tbody>\n"
      "  </table>\n"
      " </body>\n"
      "</html>\n", stdout);

    return 0; 
}


Java

Example.ejava
<%
import java.util.*;

public class Example {
  private String user;
  private String[] list;
  public example(String user, String[] list) {
    this.user = user;
    this.list = list;
  }

  public String view() {
    StringBuffer _buf = new StringBuffer();
%>
<html>
 <body>
  <p>Hello <%= user %>!</p>
  <table>
   <tbody>
    <% for (int i = 0; i < list.length; i++) { %>
    <tr bgcolor="<%= i % 2 == 0 ? "#FFCCCC" : "#CCCCFF" %>">
     <td><%= i + 1 %></td>
     <td><%== list[i] %></td>
    </tr>
    <% } %>
   </tbody>
  </table>
 <body>
</html>
<%
    return _buf.toString();
  }

  public static void main(String[] args) {
    String[] list = { "<aaa>", "b&b", "\"ccc\"" };
    Example ex = Example.new("Erubis", list);
    System.out.print(ex.view());
  }

  public static String escape(String s) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);
      switch (ch) {
      case '<':   sb.append("&lt;"); break;
      case '>':   sb.append("&gt;"); break;
      case '&':   sb.append("&amp;"); break;
      case '"':   sb.append("&quot;"); break;
      default:    sb.append(ch);
      }
    }
    return sb.toString();
  }
}
%>
compiled source code
$ erubis -b -l java example.ejava
StringBuffer _buf = new StringBuffer();
import java.util.*;

public class Example {
  private String user;
  private String[] list;
  public example(String user, String[] list) {
    this.user = user;
    this.list = list;
  }

  public String view() {
    StringBuffer _buf = new StringBuffer();

_buf.append("<html>\n"
          + " <body>\n"
          + "  <p>Hello "); _buf.append(user); _buf.append("!</p>\n"
          + "  <table>\n"
          + "   <tbody>\n");
     for (int i = 0; i < list.length; i++) { 
_buf.append("    <tr bgcolor=\""); _buf.append(i % 2 == 0 ? "#FFCCCC" : "#CCCCFF"); _buf.append("\">\n"
          + "     <td>"); _buf.append(i + 1); _buf.append("</td>\n"
          + "     <td>"); _buf.append(escape(list[i])); _buf.append("</td>\n"
          + "    </tr>\n");
     } 
_buf.append("   </tbody>\n"
          + "  </table>\n"
          + " <body>\n"
          + "</html>\n");

    return _buf.toString();
  }

  public static void main(String[] args) {
    String[] list = { "<aaa>", "b&b", "\"ccc\"" };
    Example ex = Example.new("Erubis", list);
    System.out.print(ex.view());
  }

  public static String escape(String s) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);
      switch (ch) {
      case '<':   sb.append("&lt;"); break;
      case '>':   sb.append("&gt;"); break;
      case '&':   sb.append("&amp;"); break;
      case '"':   sb.append("&quot;"); break;
      default:    sb.append(ch);
      }
    }
    return sb.toString();
  }
}

return _buf.toString();

Scheme

example.escheme
<html>
 <body>
<%
(let ((user "Erubis")
      (items '("<aaa>" "b&b" "\"ccc\""))
      (i 0))
 %>
  <p>Hello <%= user %>!</p>
  <table>
<%
  (for-each
   (lambda (item)
     (set! i (+ i 1))
 %>
   <tr bgcolor="<%= (if (= (modulo i 2) 0) "#FFCCCC" "#CCCCFF") %>">
    <td><%= i %></td>
    <td><%= item %></td>
   </tr>
<%
   ) ; lambda end
   items) ; for-each end
 %>
  </table>
<%
) ; let end
%>
 </body>
</html>
compiled source code
$ erubis -l scheme example.escheme
(let ((_buf '())) (define (_add x) (set! _buf (cons x _buf))) (_add "<html>
 <body>\n")

(let ((user "Erubis")
      (items '("<aaa>" "b&b" "\"ccc\""))
      (i 0))
 
(_add "  <p>Hello ")(_add user)(_add "!</p>
  <table>\n")

  (for-each
   (lambda (item)
     (set! i (+ i 1))
 
(_add "   <tr bgcolor=\"")(_add (if (= (modulo i 2) 0) "#FFCCCC" "#CCCCFF"))(_add "\">
    <td>")(_add i)(_add "</td>
    <td>")(_add item)(_add "</td>
   </tr>\n")

   ) ; lambda end
   items) ; for-each end
 
(_add "  </table>\n")

) ; let end

(_add " </body>
</html>\n")
  (reverse _buf))
compiled source code (with --func=display property)
$ erubis -l scheme --func=display example.escheme
(display "<html>
 <body>\n")

(let ((user "Erubis")
      (items '("<aaa>" "b&b" "\"ccc\""))
      (i 0))
 
(display "  <p>Hello ")(display user)(display "!</p>
  <table>\n")

  (for-each
   (lambda (item)
     (set! i (+ i 1))
 
(display "   <tr bgcolor=\"")(display (if (= (modulo i 2) 0) "#FFCCCC" "#CCCCFF"))(display "\">
    <td>")(display i)(display "</td>
    <td>")(display item)(display "</td>
   </tr>\n")

   ) ; lambda end
   items) ; for-each end
 
(display "  </table>\n")

) ; let end

(display " </body>
</html>\n")

Perl

example.eprl
<%
   my $user = 'Erubis';
   my @list = ('<aaa>', 'b&b', '"ccc"');
%>
<html>
 <body>
  <p>Hello <%= $user %>!</p>
  <table>
   <% $i = 0; %>
   <% for $item (@list) { %>
   <tr bgcolor=<%= ++$i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
    <td><%= $i %></td>
    <td><%= $item %></td>
   </tr>
   <% } %>
  </table>
 </body>
</html>
compiled source code
$ erubis -l perl example.eperl
use HTML::Entities; 
   my $user = 'Erubis';
   my @list = ('<aaa>', 'b&b', '"ccc"');

print('<html>
 <body>
  <p>Hello '); print($user); print('!</p>
  <table>
');     $i = 0; 
    for $item (@list) { 
print('   <tr bgcolor='); print(++$i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'); print('">
    <td>'); print($i); print('</td>
    <td>'); print($item); print('</td>
   </tr>
');     } 
print('  </table>
 </body>
</html>
'); 

JavaScript

example.ejs
<%
   var user = 'Erubis';
   var list = ['<aaa>', 'b&b', '"ccc"'];
 %>
<html>
 <body>
  <p>Hello <%= user %>!</p>
  <table>
   <tbody>
    <% var i; %>
    <% for (i = 0; i < list.length; i++) { %>
    <tr bgcolor="<%= i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
     <td><%= i + 1 %></td>
     <td><%= list[i] %></td>
    </tr>
    <% } %>
   </tbody>
  </table>
 </body>
</html>
compiled source code
$ erubis -l js example.ejs
var _buf = [];
   var user = 'Erubis';
   var list = ['<aaa>', 'b&b', '"ccc"'];
 
_buf.push("<html>\n\
 <body>\n\
  <p>Hello "); _buf.push(user); _buf.push("!</p>\n\
  <table>\n\
   <tbody>\n");
     var i; 
     for (i = 0; i < list.length; i++) { 
_buf.push("    <tr bgcolor=\""); _buf.push(i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'); _buf.push("\">\n\
     <td>"); _buf.push(i + 1); _buf.push("</td>\n\
     <td>"); _buf.push(list[i]); _buf.push("</td>\n\
    </tr>\n");
     } 
_buf.push("   </tbody>\n\
  </table>\n\
 </body>\n\
</html>\n");
document.write(_buf.join(""));


Other Topics

TinyEruby class

TinyEruby class in 'erubis/tiny.rb' is the smallest implementation of eRuby. If you don't need any enhancements of Erubis and only require simple eRuby implementation, try TinyEruby class.


Ruby on Rails Support

Erubis supports Ruby on Rails. Add the following code to your 'app/controllers/application.rb'.

app/controllers/application.rb
require 'erubis/helper/rails'
suffix = 'erubis' 
ActionView::Base.register_template_handler(suffix, Erubis::Helper::RailsTemplate)
#Erubis::Helper::RailsTemplate.engine_class = Erubis::EscapedEruby ## or Erubis::PI::Eruby
#Erubis::Helper::RailsTemplate.default_properties = { :escape=>true, :escapefunc=>'h' }

If you specify Erubis::Helper::CachedRailsTemplate class instead of Erubis::Helper::RailsTemplate class, template string is cached in memory (but template is not reloaded when it is modified).

You may got the followign error:

(eval):10:in `render': no block given

It is because layout file scaffold created contains 'yield' method. Use '@content_for_layout' instead 'yield'.

app/views/layouts/xxx.erubis
  ...
  <%#= yield %>
  <%= @content_for_layout %>
  ...

NoTextEnhancer and NoCodeEnhancer in PHP

NoTextEnhancer and NoCodEnahncer are quite useful not only for eRuby but also for PHP. The former "drops" HTML text and show up embedded Ruby/PHP code and the latter drops embedded Ruby/PHP code and leave HTML text.

For example, see the following PHP script.

notext-example.php
<html>
  <body>
    <h3>List</h3>
    <?php if (!$list || count($list) == 0) { ?>
    <p>not found.</p>
    <?php } else { ?>
    <table>
      <tbody>
        <?php $i = 0; ?>
        <?php foreach ($list as $item) { ?>
        <tr bgcolor="<?php echo ++$i % 2 == 1 ? '#FFCCCC' : '#CCCCFF'; ?>">
          <td><?php echo $item; ?></td>
        </tr>
        <?php } ?>
      </tbody>
    </table>
    <?php } ?>
  </body>
</html>

This is complex because PHP code and HTML document are mixed. NoTextEnhancer can separate PHP code from HTML document.

example of using NoTextEnhancer with PHP file
$ erubis -T -l php -E NoText -p '<\?php \?>' notext-example.php | cat -n
     1	
     2	
     3	
     4	    <?php if (!$list || count($list) == 0) { ?>
     5	
     6	    <?php } else { ?>
     7	
     8	
     9	        <?php $i = 0; ?>
    10	        <?php foreach ($list as $item) { ?>
    11	                     <?php echo ++$i % 2 == 1 ? '#FFCCCC' : '#CCCCFF'; ?>
    12	              <?php echo $item; ?>
    13	
    14	        <?php } ?>
    15	
    16	
    17	    <?php } ?>
    18	
    19	

In the same way, NoCodeEnhancer can extract HTML tags.

example of using NoCodeEnhancer with PHP file
$ erubis -T -l php -E NoCode -p '<\?php \?>' notext-example.php | cat -n
     1	<html>
     2	  <body>
     3	    <h3>List</h3>
     4	    
     5	    <p>not found.</p>
     6	    
     7	    <table>
     8	      <tbody>
     9	        
    10	        
    11	        <tr bgcolor="">
    12	          <td></td>
    13	        </tr>
    14	        
    15	      </tbody>
    16	    </table>
    17	    
    18	  </body>
    19	</html>

Command notext

Command 'notext' removes text part from eRuby script and leaves only embedded Ruby code. This is very useful when debugging eRuby script.

notext-ex.rhtml
<html>
 <head>
  <title>notext example</title>
 </head>
 <body>
  <table>
<% @list.each_with_index do |item, i| %>
<%   klass = i % 2 == 0 ? 'odd' : 'even' %>
   <tr class="<%= klass %>">
    <td><%== item %></td>
   </tr>
<% end %>
  </table>
 </body>
</html>
command line example
$ notext notext-ex.rhtml
_buf = [];





 @list.each_with_index do |item, i| ;
   klass = i % 2 == 0 ? 'odd' : 'even' ;
               _buf << ( klass ).to_s;
         _buf << Erubis::XmlHelper.escape_xml( item );

 end ;


_buf.join

Command-line option '-u' deletes continuous empty lines to one empty line.

command-line example
$ notext -u notext-ex.rhtml
_buf = [];

 @list.each_with_index do |item, i| ;
   klass = i % 2 == 0 ? 'odd' : 'even' ;
               _buf << ( klass ).to_s;
         _buf << Erubis::XmlHelper.escape_xml( item );

 end ;

_buf.join

Command-line option '-c' deletes all empty lines.

command-line example
$ notext -c notext-ex.rhtml
_buf = [];
 @list.each_with_index do |item, i| ;
   klass = i % 2 == 0 ? 'odd' : 'even' ;
               _buf << ( klass ).to_s;
         _buf << Erubis::XmlHelper.escape_xml( item );
 end ;
_buf.join

Command-line option '-n' shows line numbers. It can work with '-c' or '-u'.

$ notext -nu example2.rhtml
  1: _buf = [];

  7:  @list.each_with_index do |item, i| ;
  8:    klass = i % 2 == 0 ? 'odd' : 'even' ;
  9:                _buf << ( klass ).to_s;
 10:          _buf << Erubis::XmlHelper.escape_xml( item );

 12:  end ;

 16: _buf.join
$ notext -nc example2.rhtml
  1: _buf = [];
  7:  @list.each_with_index do |item, i| ;
  8:    klass = i % 2 == 0 ? 'odd' : 'even' ;
  9:                _buf << ( klass ).to_s;
 10:          _buf << Erubis::XmlHelper.escape_xml( item );
 12:  end ;
 16: _buf.join

Command 'notext' supports '-l lang' options. For example, command-line option '-l php' retrieves embedded PHP code from PHP file.


Benchmark

A benchmark script is included in Erubis package at erubis-X.X.X/benchark directory. Here is an example result of benchmark.

Env: Linux FedoraCore4, Celeron 667MHz, Mem512MB, Ruby1.8.4, eruby1.0.5
                                        user     system      total        real
ERuby                             131.990000   1.900000 133.890000 (135.061456)
ERB                               385.040000   3.180000 388.220000 (391.570653)
Erubis::Eruby                     127.750000   2.520000 130.270000 (131.385922)
Erubis::StringBufferEruby         167.610000   2.600000 170.210000 (171.712798)
Erubis::StdoutEruby                92.790000   2.000000  94.790000 ( 95.532633)
Erubis::TinyEruby                 118.720000   2.250000 120.970000 (122.022996)
Erubis::TinyStdoutEruby            87.130000   2.030000  89.160000 ( 89.879538)
Env: MacOS X 10.4, PowerPC 1.42GHz, Mem1.5GB, Ruby1.8.4, eruby1.0.5
                                        user     system      total        real
ERuby                              55.040000   2.120000  57.160000 ( 89.311397)
ERB                               103.960000   3.480000 107.440000 (159.231792)
Erubis::Eruby                      36.130000   1.570000  37.700000 ( 52.188574)
Erubis::StringBufferEruby          47.270000   1.980000  49.250000 ( 73.867537)
Erubis::StdoutEruby                26.240000   1.490000  27.730000 ( 41.840430)
Erubis::TinyEruby                  31.690000   1.590000  33.280000 ( 49.862091)
Erubis::TinyStdoutEruby            22.550000   1.230000  23.780000 ( 33.316978)

This shows that:



Command Reference

Usage

erubis [..options..] [file ...]


Options

-h, --help
Help.
-v
Release version.
-x
Show compiled source.
-T
No trimming spaces around '<% %>'. This is equivarent to '--trim=false'.
-b
Body only (no preamble nor postamble). This is equivarent to '--preamble=false --postamble=false'.
-e
Escape. This is equivarent to '-E Escape'.
-p pattern
Embedded pattern (default '<% %>'). This is equivarent to '--pattern=pattern'.
-l lang
Language name. This option makes erubis command to compile script but no execute.
-E enhacers
Enhancer name (Escape, PercentLine, ...). It is able to specify several enhancer name separating with ',' (ex. -f Escape,PercentLine,HeaderFooter).
-I path
Require library path ($:). It is able to specify several paths separating with ',' (ex. -f path1,path2,path3).
-K kanji
Kanji code (euc, sjis, utf8, or none) (default none).
-f file.yaml
YAML file for context values (read stdin if filename is '-'). It is able to specify several filenames separating with ',' (ex. -f file1,file2,file3).
-t
Expand tab characters in YAML file.
-S
Convert mapping key from string to symbol in YAML file.
-B
invoke Eruby#result() instead of Eruby#evaluate()
--pi[=name]
parse '<?name ... ?>' instead of '<% ... %>'

Properties

Some Eruby classes can take optional properties to change it's compile option. For example, property '--indent=" "' may change indentation of compiled source code. Try 'erubis -h' for details.