module EJS
def compile(source, options = {})
# => "function(obj){...}"
EJS.compile("Hello <%= name %>")
template.
`compile` if you want to specify a different tag syntax for the
`:evaluation_pattern` and `:interpolation_pattern` options to
variables in the template. You can optionally pass the
function takes an optional argument, an object specifying local
Compiles an EJS template to a JavaScript function. The compiled
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
def escape_function
def escape_function ".replace(/&/g, '&')" + ".replace(/</g, '<')" + ".replace(/>/g, '>')" + ".replace(/\"/g, '"')" + ".replace(/'/g, ''')" + ".replace(/\\//g,'/')" end
def evaluate(template, locals = {}, options = {})
# => "Hello world"
EJS.evaluate("Hello <%= name %>", :name => "world")
JavaScript runtime available.
(https://github.com/sstephenson/execjs/) library and a
compiler options. You will need the ExecJS
Evaluates an EJS template with the given local variables and
def evaluate(template, locals = {}, options = {}) require "execjs" context = ExecJS.compile("var evaluate = #{compile(template, options)}") context.call("evaluate", locals) end
def js_escape!(source)
def js_escape!(source) source.gsub!(JS_ESCAPE_PATTERN) { |match| '\\' + JS_ESCAPES[match] } source end
def js_unescape!(source)
def js_unescape!(source) source.gsub!(JS_UNESCAPE_PATTERN) { |match| JS_UNESCAPES[match[1..-1]] } source end
def replace_escape_tags!(source, options)
def replace_escape_tags!(source, options) source.gsub!(options[:escape_pattern] || escape_pattern) do "',(''+#{js_unescape!($1)})#{escape_function},'" end end
def replace_evaluation_tags!(source, options)
def replace_evaluation_tags!(source, options) source.gsub!(options[:evaluation_pattern] || evaluation_pattern) do "'); #{js_unescape!($1)}; __p.push('" end end
def replace_interpolation_tags!(source, options)
def replace_interpolation_tags!(source, options) source.gsub!(options[:interpolation_pattern] || interpolation_pattern) do "', #{js_unescape!($1)},'" end end