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
-
.escape_pattern ⇒ Object
Returns the value of attribute escape_pattern.
-
.evaluation_pattern ⇒ Object
Returns the value of attribute evaluation_pattern.
-
.interpolation_pattern ⇒ Object
Returns the value of attribute interpolation_pattern.
Class Method Summary collapse
-
.compile(source, options = {}) ⇒ Object
Compiles an EJS template to a JavaScript function.
-
.evaluate(template, locals = {}, options = {}) ⇒ Object
Evaluates an EJS template with the given local variables and compiler options.
Class Attribute Details
.escape_pattern ⇒ Object
Returns the value of attribute escape_pattern.
22 23 24 |
# File 'lib/ejs.rb', line 22 def escape_pattern @escape_pattern end |
.evaluation_pattern ⇒ Object
Returns the value of attribute evaluation_pattern.
20 21 22 |
# File 'lib/ejs.rb', line 20 def evaluation_pattern @evaluation_pattern end |
.interpolation_pattern ⇒ Object
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, = {}) source = source.dup js_escape!(source) (source, ) (source, ) (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"
53 54 55 56 57 |
# File 'lib/ejs.rb', line 53 def evaluate(template, locals = {}, = {}) require "execjs" context = ExecJS.compile("var evaluate = #{compile(template, )}") context.call("evaluate", locals) end |