Module: EJS

Defined in:
lib/ejs.rb

Overview

EJS (Embedded JavaScript) template compiler for Ruby This is a port of Underscore.js’ ‘_.template` function: documentcloud.github.com/underscore/

Constant Summary collapse

JS_UNESCAPES =
{
  '\\' => '\\',
  "'" => "'",
  'r' => "\r",
  'n' => "\n",
  't' => "\t",
  'u2028' => "\u2028",
  'u2029' => "\u2029"
}
JS_ESCAPES =
JS_UNESCAPES.invert
JS_UNESCAPE_PATTERN =
/\\(#{Regexp.union(JS_UNESCAPES.keys)})/
JS_ESCAPE_PATTERN =
Regexp.union(JS_ESCAPES.keys)

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.escape_patternObject

Returns the value of attribute escape_pattern.



22
23
24
# File 'lib/ejs.rb', line 22

def escape_pattern
  @escape_pattern
end

.evaluation_patternObject

Returns the value of attribute evaluation_pattern.



20
21
22
# File 'lib/ejs.rb', line 20

def evaluation_pattern
  @evaluation_pattern
end

.interpolation_patternObject

Returns the value of attribute interpolation_pattern.



21
22
23
# File 'lib/ejs.rb', line 21

def interpolation_pattern
  @interpolation_pattern
end

Class Method Details

.compile(source, options = {}) ⇒ Object

Compiles an EJS template to a JavaScript function. The compiled function takes an optional argument, an object specifying local variables in the template. You can optionally pass the ‘:evaluation_pattern` and `:interpolation_pattern` options to `compile` if you want to specify a different tag syntax for the template.

EJS.compile("Hello <%= name %>")
# => "function(obj){...}"


34
35
36
37
38
39
40
41
42
43
# File 'lib/ejs.rb', line 34

def compile(source, options = {})
  source = source.dup

  js_escape!(source)
  replace_escape_tags!(source, options)
  replace_interpolation_tags!(source, options)
  replace_evaluation_tags!(source, options)
  "function(obj){var __p=[],print=function(){__p.push.apply(__p,arguments);};" +
    "with(obj||{}){__p.push('#{source}');}return __p.join('');}"
end

.evaluate(template, locals = {}, options = {}) ⇒ Object

Evaluates an EJS template with the given local variables and compiler options. You will need the ExecJS (github.com/sstephenson/execjs/) library and a JavaScript runtime available.

EJS.evaluate("Hello <%= name %>", :name => "world")
# => "Hello world"


53
54
55
56
57
# File 'lib/ejs.rb', line 53

def evaluate(template, locals = {}, options = {})
  require "execjs"
  context = ExecJS.compile("var evaluate = #{compile(template, options)}")
  context.call("evaluate", locals)
end