Module: Underscore::Engine

Defined in:
lib/underscore-template/engine.rb

Overview

UnderscoreTemplate (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)
EVALUATION_PATTERN =
/<%([\s\S]+?)%>/
INTERPOLATION_PATTERN =
/<%=([\s\S]+?)%>/
ESCAPE_PATTERN =
/<%-([\s\S]+?)%>/

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.underscore_availableObject

Returns the value of attribute underscore_available.



27
28
29
# File 'lib/underscore-template/engine.rb', line 27

def underscore_available
  @underscore_available
end

Class Method Details

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

Compiles an UnderscoreTemplate template to a JavaScript function. The compiled function takes an optional argument, an object specifying local variables in the template.

> Underscore::Engine.compile("Hello <%= name %>")
#  => "function(obj){\nvar __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};\nwith(obj||{}){\n__p+='Hello '+\n( name )+\n'\\n';\n}\nreturn __p;\n}"


36
37
38
39
# File 'lib/underscore-template/engine.rb', line 36

def compile(source, options = {})
  template_func = precompile(source, options)
  underscore_context.eval("#{template_func}.source")
end

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

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

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


60
61
62
63
64
# File 'lib/underscore-template/engine.rb', line 60

def evaluate(template, locals = {}, options = {})
  template_to_compile = compile(template, options)

  underscore_context.call(template_to_compile, locals)
end

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

Safely duplicates the source file and converts it to a call to UnderscoreJS’ template function

UnderscoreTemplate.compile("Hello <%= name %>")
# => "_.template('Hello <%= name %>')"


46
47
48
49
50
# File 'lib/underscore-template/engine.rb', line 46

def precompile(source, options = {})
  source = ::Haml::Engine.new(source.dup).render
  js_escape!(source)
  "_.template(\"#{source}\")"
end