Module: EJS

Defined in:
lib/ejs.rb

Overview

EJS (Embedded JavaScript) template compiler for Ruby © 2011 Sam Stephenson

This is a port of Underscore.js’ _.template function: documentcloud.github.com/underscore/

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.evaluation_patternObject

Returns the value of attribute evaluation_pattern.



9
10
11
# File 'lib/ejs.rb', line 9

def evaluation_pattern
  @evaluation_pattern
end

.interpolation_patternObject

Returns the value of attribute interpolation_pattern.



10
11
12
# File 'lib/ejs.rb', line 10

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){...}"


22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ejs.rb', line 22

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

  escape_quotes!(source)
  replace_interpolation_tags!(source, options)
  replace_evaluation_tags!(source, options)
  escape_whitespace!(source)

  "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"


42
43
44
45
46
# File 'lib/ejs.rb', line 42

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