Erubis-J Users' Guide

2   Guide for Users

2-1   Embedded Pattern

Here is the notation of embedded JavaScript code.

  • <% ... %> represents statement code.
  • <%= ... %> represents expression code.
  • <%== ... %> represents expression code which is escaped.
  • <%=== ... %> represents expression debug print.
  • <%# ... %> represents comment out.
ex1.ejs:
<%
   var title = 'Erubis Example';
   var list = [ 'str', 123, true, null ];
 %>
<h1><%= title %></h1>
<ul>
<% for (var i = 0, n = list.length; i < n; i++) { %>
  <li><%= list[i] %></li>
<% } %>
<ul>
<%# this line will not displayed. %>
result:
$ java erubis.Main ex1.ejs
<h1>Erubis Example</h1>
<ul>
  <li>str</li>
  <li>123</li>
  <li>true</li>
  <li></li>
<ul>

If the file contains non-ascii characters, you must specify the command-line option '-k encoding'.

$ java erubis.Main -k EUC-JP ex1.ejs   # or Shift_JIS, UTF8, and so on

2-2   Show JavaScript Code

Command-line option '-x' shows the converted JavaScript code.

ex2.ejs:
<html>
 <body>
  <ul>
   <% for (var i = 0, n = list.length; i < n; i++) { %>
   <li><%= list[i] %></li>
   <% } %>
  <ul>
 </body>
</html>
result:
$ java erubis.Main -x ex2.ejs
var _buf = []; _buf.push("<html>\n\
 <body>\n\
  <ul>\n");
    for (var i = 0, n = list.length; i < n; i++) { 
_buf.push("   <li>"); _buf.push(list[i]); _buf.push("</li>\n");
    } 
_buf.push("  <ul>\n\
 </body>\n\
</html>\n");
_buf.join('')

The first statement ('var _buf = [];') is called "preamble", and the last statement ('_buf.join('')') is called "postamble". Th command-line option '-b' makes not to generate preamble nor postamble.

2-3   Escape Expression

'<%= ... %>' prints expression value and '<%== ... %>' prints escaped expression value.

ex3.ejs:
<% var text = '<b>"foo" & "bar"</b>'; %>
<span><%= text %></span>
<span><%== text %></span>
result:
$ java erubis.Main ex3.ejs
<span><b>"foo" & "bar"</b></span>
<span>&lt;b&gt;&quot;foo&quot; &amp; &quot;bar&quot;&lt;/b&gt;</span>

Command-line option '-e' switches escaping '<%= %>' and '<%== %>'. It means that '<%= %>' is escaped and '<%== %>' is not escaped.

result:

$ java erubis.Main -e ex3.ejs
<span>&lt;b&gt;&quot;foo&quot; &amp; &quot;bar&quot;&lt;/b&gt;</span>
<span><b>"foo" & "bar"</b></span>

Escape function name is '_escape()' in default. It is able to change escape function name with the command-line property '--escapefunc=funcname'.

result:

$ java erubis.Main -x ex3.ejs
var _buf = [];  var text = '<b>"foo" & "bar"</b>'; 
_buf.push("<span>"); _buf.push(text); _buf.push("</span>\n\
<span>"); _buf.push(_escape(text)); _buf.push("</span>\n");
_buf.join('')

$ java erubis.Main -x --escapefunc=escapeXml ex3.ejs
var _buf = [];  var text = '<b>"foo" & "bar"</b>'; 
_buf.push("<span>"); _buf.push(text); _buf.push("</span>\n\
<span>"); _buf.push(escapeXml(text)); _buf.push("</span>\n");
_buf.join('')

2-4   Changing Embedded Pattern

Command-line property '--pattern=pattern' changes embedded pattern.

ex4.ejs:
[%
   var title = 'Erubis Example';
   var list = [ 'str', 123, true, null ];
 %]
<h1>[%= title %]</h1>
<ul>
[% for (var i = 0, n = list.length; i < n; i++) { %]
  <li>[%= list[i] %]</li>
[% } %]
<ul>
result:
$ java erubis.Main --pattern='\[% %\]' ex4.ejs
<h1>Erubis Example</h1>
<ul>
  <li>str</li>
  <li>123</li>
  <li>true</li>
  <li></li>
<ul>

Notice that some characters ('[ ] . * ? $ ^ { } ( ) + \') must be escaped by backslash, because the embedded pattern specified by option '-p' is used as a part of regular expression.

2-5   Processing Instructions Converter

Erubis-J supports the another notation using Processing Instructions (PI) in XML document.

  • '<?js ... ?>' represents JavaScript statement code.
  • '@{...}@' represents JavaScript escaped expression code.
  • '@!{...}@' represents JavaScript expression code.
  • '@!!{...}@' represents debug print.
ex5.xhtml:
<?xml version="1.0" encoding="UTF-8"?>
<?js
   var text = 'x > 0 && 10 < x';
   var list = [ 'foo', 'bar', 'baz' ];
?>
<html>
 <body>
  <p>escaped: @{text}@</p>
  <p>not escaped: @!{text}@</p>
  <ul>
   <?js for (var i = 0, n = list.length; i < n; i++) { ?>
   <li>@{list[i]}@</li>
   <?js } ?>
  </ul>
 </body>
</html>

The command-line property '--pi=js' makes to use PI converter.

result:
$ java erubis.Main --pi=js ex5.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<html>
 <body>
  <p>escaped: x &gt; 0 &amp;&amp; 10 &lt; x</p>
  <p>not escaped: x > 0 && 10 < x</p>
  <ul>
   <li>foo</li>
   <li>bar</li>
   <li>baz</li>
  </ul>
 </body>
</html>

Command-line option '-e' or '--escape=false' switches '@{...}@' not escaped and '@!{...}@' escaped.

It is able to change character of embedded expression pattern by '--embchar=char'. For example, '--embchar=?' parses '?{...}' pattern.

(Experimental) Erubis-J supports another PI converter.

  • '<?js ... ?>' represents JavaScript statement code.
  • '#{...}' represents JavaScript expression code.
  • '${...}' represents JavaScript escaped expression code.

This is available with command-line property '--pi2=js'. Characters of embedded expression pattern are changeable with '--embchars="#,$"'.

2-6   Context Data File

Command-line option '-f filename' specifies the context data file. Context data file format must be one of the following.

  • YAML (*.yaml)
  • JSON (*.json)
  • JavaScript (*.js)

Erubis-J detects the datafile format by suffix of filename.

ex6.ejs:
<h1><%= title %></h1>
<table>
  <tr>
    <th>Name</th><th>Age</th>
  </tr>
<% for (var i = 0, len = members.length; i < len; i++) { %>
<%    member = members[i]; %>
  <tr>
    <td><%= member.name %></td>
    <td><%= member.age %></td>
  </tr>
<% } %>
</table>
datafile.yaml:
title:  Member List
members:
  - name:  Foo
    age:   20
  - name:  Bar
    age:   22
  - name:  Baz
    age:   24
result:
$ java erubis.Main -f datafile.yaml ex6.ejs
<h1>Member List</h1>
<table>
  <tr>
    <th>Name</th><th>Age</th>
  </tr>
  <tr>
    <td>Foo</td>
    <td>20</td>
  </tr>
  <tr>
    <td>Bar</td>
    <td>22</td>
  </tr>
  <tr>
    <td>Baz</td>
    <td>24</td>
  </tr>
</table>
datafile.json:
{
  title: 'Member List',
  members: [
    { name: 'Foo', age: 20 },
    { name: 'Bar', age: 22 },
    { name: 'Baz', age: 24 }
  ]
}
result:
$ java erubis.Main -f datafile.json ex6.ejs
   ... the same output as '-f datafile.yaml' ...
datafile.js:
title = 'Member List';
members = [ { name: 'Foo', age: 20 },
            { name: 'Bar', age: 22 },
            { name: 'Baz', age: 24 }
          ];
result:
$ java erubis.Main -f datafile.js ex6.ejs
   ... the same output as '-f datafile.yaml' ...

If there are non-ascii characters in context datafile, command-line option '-k encoding' is required (such as 'EUC-JP', 'Shift_JIS', 'UTF8', and so on). The option converts encoding of datafile, input file, and output. There is no option to specify different encoding of datafile, input file, or output respectively.

2-7   Decorators

Decorator is a decoration class of code generation. Each decorator class has it's own feature.

There are three decorators are provided.

BodyOnlyDecorator
Delete preamble code ('var _buf = []; ') and postabmle code ('_buf.join('')'). The command-line option '-b' is equivarent to this decorator.
NoTextDecorator
Deletes text and prints only embedded JavaScript code. This is useful to retrieve embedded JavaScritp code and check it's syntax error.
NoCodeDecorator
Deletes embedded JavaScript code and prints only text. This is useful to retrieve HTML file from embeded JavaScript file and validate HTML syntax.

Command-line option '-d' specifies the decorators.

ex7.ejs
<ul>
<% for (int i = 0, n = list.length; i < n; i++) { %>
  <li><%= list[i] %></li>
<% } %>
</ul>
result:
$ java erubis.Main -x ex7.ejs
var _buf = []; _buf.push("<ul>\n");
 for (int i = 0, n = list.length; i < n; i++) { 
_buf.push("  <li>"); _buf.push(list[i]); _buf.push("</li>\n");
 } 
_buf.push("</ul>\n");
_buf.join('')

$ java erubis.Main -x -d BodyOnly ex7.ejs
_buf.push("<ul>\n");
 for (int i = 0, n = list.length; i < n; i++) { 
_buf.push("  <li>"); _buf.push(list[i]); _buf.push("</li>\n");
 } 
_buf.push("</ul>\n");

$ java erubis.Main -x -d NoText ex7.ejs
var _buf = []; 
 for (int i = 0, n = list.length; i < n; i++) { 
_buf.push(list[i]); 
 } 

_buf.join('')

$ java erubis.Main -x -d NoCode ex7.ejs
<ul>
  <li></li>
</ul>

2-8   Convert Java Object to JavaScript Object

Erubis-J converts Java object to JavaScript object automatically.

  • java.util.List object is converted into native array object of JavaScript(*1).
  • java.util.Map object is converted into native object of JavaScript(*2).
  • String, Integer, Float, Boolean, and null are converted into string, number, boolean, and null of JavaScript.

The command-line property '--java2js=false' suppress this conversion.

The following examples uses list.size() and list.get(i) instead of list.length and list[i] because list is an instance of java.util.List and not JavaScript native array.

ex8.ejs:
<ul>
<% for (var i = 0, n = list.size(); i < n; i++) { %>
  <li><%= list.get(i) %></li>
<% } %>
</ul>
ex8.json:
{ list: [ 'foo', 'bar', 'baz' ] }
result:
$ java erubis.Main --java2js=false -f ex8.json ex8.ejs
<ul>
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>
(*1)
org.mozilla.javascript.NativeArray object.
(*2)
org.mozilla.javascript.NativeObject object.

2-9   Multi-Language

Erubis-J supports multi-language. Currently the followings are supported.

  • Java
  • C
  • Ruby

Command-line option '-l lang' switches the language.

Notice that only convertion are supported for these languages. Evaluation is not supported. You must specify '-x' option when using '-l lang'.

The following is an exmple of embedded Java text.

ex9.ejava
<html>
 <body>
  <ul>
<% for (Iterator it = list.iterator(); it.hasNext(); ) { %>
<%   Object item = it.next(); %>
  <li><%= item %></li>
      <%=== item %>
<% } %>
  </ul>
 </body>
</html>
result:
$ java erubis.Main -l java -x ex9.ejava
StringBuffer _buf = new StringBuffer(); _buf.append("<html>\n"
          + " <body>\n"
          + "  <ul>\n");
 for (Iterator it = list.iterator(); it.hasNext(); ) { 
   Object item = it.next(); 
_buf.append("  <li>"); _buf.append(item); _buf.append("</li>\n");
_buf.append("      "); System.err.println("*** debug: item="+(item)); _buf.append("\n");
 } 
_buf.append("  </ul>\n"
          + " </body>\n"
          + "</html>\n");
System.out.print(_buf.toString());

The following is an exmple of embedded C text.

  • '<%= expr %>' and <%== expr %> are printed as string.
  • '<%= "%x", expr %>' and '<%= "%x", expr %>' are printed with printf() function.
ex9.ec
<%
#include <stdio.h>

int main(int argc, char *argv[]) {
    int i;
%>
<html>
 <body>
  <table>
<% for (i = 0; i < argv; i++) { %>
   <tr>
    <td>i = <%= "%d", i %></td>
    <td>argv[i] = <%= argv[i] %></td>
    <td>escaped: <%== argv[i] %></td>
    <td>escaped with format: <%== "%10s", argv[i] %></td>
   </tr>
<% } %>
  </table>
 </body>
</html>
<%
    return 0;
}
%>
result:
$ java erubis.Main -l c -x ex9.ec

#include <stdio.h>

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

fputs("<html>\n"
      " <body>\n"
      "  <table>\n", stdout);
 for (i = 0; i < argv; i++) { 
fputs("   <tr>\n"
      "    <td>i = ", stdout); printf("%d", i); fputs("</td>\n"
      "    <td>argv[i] = ", stdout); fputs(argv[i], stdout); fputs("</td>\n"
      "    <td>escaped: ", stdout); fputs(_escape(argv[i]), stdout); fputs("</td>\n"
      "    <td>escaped with format: ", stdout); printf("%10s", _escape(argv[i])); fputs("</td>\n"
      "   </tr>\n", stdout);
 } 
fputs("  </table>\n"
      " </body>\n"
      "</html>\n", stdout);

    return 0;
}

If you want not to print preamble (ex. 'StringBuffer _buf = new StringBuffer();') nor postamble (ex. 'System.out.print(_buf.toString())'), use command-line option '-b'.

The command-line property '--pi' and '--pi2' are also available with '-l lang'.

2-10   Filter

The command-line option '-g filter' specifies output filter ('*.js' or '*.ejs'). Filter is a script to manipulate output of converter or processor.

Currently the following filters are provided.

javaclass.js
Create Java class from embedded text file.

These filters are in 'filter' directory.

2-10-1   javasclass.js

Filter 'javaclass.js' creates Java class from embedded text file.

The following is an example.

MyPage.html
<?java
   /*
    *  set directives.
    */
   //@package my.pkg.foo;
   //#@class   MyPage;
   //#@parent  erubis.page.XmlPage;
   //@import  my.pkg.bar;
   //@import  my.pkg.baz;
   //@param   String title = "Filter Example";
   //@param   List   list;
?>
<html>
 <body>
  <h1>@!{title}@</h1>
  <ul>
<?java for (Iterator it = list.iterator(); it.hasNext(); ) { ?>
<?java    Object item = it.next(); ?>
   <li>@!{item}@</li>
<?java } ?>
  </ul>
 </body>
</html>
result:
$ java erubis.Main -bxl java --pi=java -k UTF8 -g filter/javaclass.js MyPage.html
package my.pkg.foo;
import java.util.*;
import my.pkg.bar;
import my.pkg.baz;
public class MyPage {
     public void create(StringBuffer _buf) { 
   /*
    *  set directives.
    */
   //@package my.pkg.foo;
   //#@class   MyPage;
   //#@parent  erubis.page.XmlPage;
   //@import  my.pkg.bar;
   //@import  my.pkg.baz;
   //@param   String title = "Filter Example";
   //@param   List   list;

_buf.append("<html>\n"
          + " <body>\n"
          + "  <h1>"); _buf.append(title); _buf.append("</h1>\n"
          + "  <ul>\n");
 for (Iterator it = list.iterator(); it.hasNext(); ) { 
    Object item = it.next(); 
_buf.append("   <li>"); _buf.append(item); _buf.append("</li>\n");
 } 
_buf.append("  </ul>\n"
          + " </body>\n"
          + "</html>\n");
    }

    // this method is generated only when '//@parent' is not specified.
    public String create() {
        StringBuffer _buf = new StringBuffer(2048);
        create(_buf);
        return _buf.toString();
    }

    // this method is generated only when '//@parent' is not specified.
    public static String _escape(String str) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0, len = str.length(); i < len; i++) {
            char ch = str.charAt(i);
            switch (ch) {
            case '&':  sb.append("&amp;");  break;
            case '<':  sb.append("&lt;");   break;
            case '>':  sb.append("&gt;");   break;
            case '"':  sb.append("&quot;"); break;
            case '\'': sb.append("&#039;"); break;
            default:   sb.append(ch);       break;
            }
        }
        return str.toString();
    }


    private String title = "Filter Example";
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    private List list;
    public List getList() { return list; }
    public void setList(List list) { this.list = list; }

}

Directives are command to control 'javaclass.js' filter. Notation of directive is '//@name arg...;'. The following directives are available with 'javaclass.js' filter.

//@package name;
Package name. Default is none.
//@class name;
Class name. Default is filename (for example, filename is 'Foo.html' then class name is 'Foo').
//@parent name;
Parent class name. Default is none. Erubis-J provides the utility interface 'erubis.page.Page' and it's subclasses. If 'erubis.page.Xxx' is specified, 'erubis.page.Page#set(name, value)' methods are defined automatically.
//@import library;
Import library name. 'java.util.*' is automatically imported.
//@param type name [= initval];
Parameters. These are instance variables of the class. Setter methods are defined automatically.

The following command-line properties are available.

--class=name
Class name. Overrides //@class directive.
--package=name
Package name. Overrides //@package directive.
--parent=name
Parent class name. Overrides //@parent directive.
--write=true
Create and write Java file.
--root=path
Root directory to create Java files.
--defset=true
Define 'erubis.page.Page#set(name, value)' methods automatically. Default is true only when parent class name is 'erubis.page.Xxxx'.

The following is an example to create *.java files from *.html files.

$ java erubis.Main -bxl java --pi=java -k UTF8 -g filter/javaclass.js \
     --write=true --root=src/page *.html