Skip to content

Instantly share code, notes, and snippets.

@mcmire
Created December 13, 2011 06:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcmire/1470966 to your computer and use it in GitHub Desktop.
Save mcmire/1470966 to your computer and use it in GitHub Desktop.
Integrating Handlebars into Jammit
(function(jq) {
window.Jammit = {
// At the top of the Javascript file that Jammit assembles, this function is
// called once for each Mustache template that Jammit encounters. It does two
// things:
//
// 1) It tells Handlebars about the template by putting its raw content in
// Handlebars.partials. This makes it possible for any Mustache template
// to refer to another via a partial.
// 2) It stores the render function for the template in the global JST
// object, so that you can actually render the template in your code.
//
// name - The String name of a template, to be stored under JST.
// May contain slashes (e.g. "foo/bar").
// content - A String Mustache template.
//
// Returns nothing.
//
storeTemplate: function(name, content) {
// Add the template content to the list of Handlebars partials.
// Convert slashes to dots in the template name because this is how
// Handlebars resolves partial names.
Handlebars.partials[name.replace(/\//g, ".")] = content;
// Compile the template right away so that future calls do not have to do
// this. Handlebars.compile() returns a function that can then be called to
// render the template - such as `JST[name](data, options)`.
var render = Handlebars.compile(content);
JST[name] = function(context, options) {
if (arguments.length) {
// Render the template to a string.
return render(context, options);
}
else {
// Return the raw template with no arguments. This is useful (??) for
// rendering partials. (Here for backward compatibility.)
return content;
}
}
}
};
})(window.jQuery);
module Jammit
class Compressor
# Override so that instead of directly setting JST[name], we call a custom
# Javascript function which will do two things: 1) store the raw content of
# each template and give it to Handlebars in such a way that partials will
# work; and 2) precompile templates so that rendering them is faster.
#
def compile_jst(paths)
namespace = Jammit.template_namespace
paths = paths.grep(Jammit.template_extension_matcher).sort
base_path = find_base_path(paths)
compiled = paths.map do |path|
contents = read_binary_file(path)
contents = contents.gsub(/\r?\n/, "\\n").gsub("'", '\\\\\'')
name = template_name(path, base_path)
"Jammit.storeTemplate('#{name}', '#{contents}');"
end
compiler = Jammit.include_jst_script ? read_binary_file(DEFAULT_JST_SCRIPT) : '';
setup_namespace = "#{namespace} = #{namespace} || {};"
[JST_START, setup_namespace, compiler, compiled, JST_END].flatten.join("\n")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment