Created
February 23, 2011 18:06
-
-
Save mrjjwright/840846 to your computer and use it in GitHub Desktop.
Add partials, layouts to underscore.js templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Caches, renders, ands adds supports for partials and layout to underscore.js templating | |
# | |
# Pass in one options object to renderTemplate: | |
# dir: the root dir where all the templates are located, defaults to views. Paths are resolved as e.g dir/partial.html or dir/layout.html. | |
# partial(s): one or more partial names (without the *.html) to compile, cache, render, and optionally return. | |
# If layout is present, the partials will be passed to the layout template with keys as the partial names | |
# and the layout html will be returned. | |
# partialPrefix: (optional) a name to prepend to all partials. E.g. passing in "products." will load dir/products.partial.html | |
# layout: the name of a layout template (without the *.html). If missing the last or only partial html will be returned. | |
# context: a context object to pass to each partial and layout. The underscore object is passed by default as "_". | |
templateCache = templateCache ? {} | |
loadFromTemplateCache = (path) -> | |
if env.indexOf "dev" != -1 | |
return _.template(fs.readFileSync(path, 'utf8')) | |
return templateCache[path] ? templateCache[path] = _.template(fs.readFileSync(path, 'utf8')) | |
renderTemplate = (options) -> | |
# Sort out the options. | |
rootDir = options.dir ? "./views" | |
context = options.context ? {} | |
partialPrefix = options.partialPrefix ? "" | |
partials = _.flatten(options.partials ? [options.partial]) | |
# Pass in underscore to the template. | |
context["_"] = _ | |
# Render the partials | |
partialHTML = "" | |
if partials? | |
for partial in partials | |
partialHTML = loadFromTemplateCache("#{rootDir}/#{partialPrefix}#{partial}.html")(context) | |
# Optionally, add the partials to the conect | |
if options.layout? then context[partial] = partialHTML | |
if options.layout? | |
# Render and return the layout. | |
return loadFromTemplateCache("#{rootDir}/#{options.layout}.html")(context) | |
else | |
# Return the last or only partial | |
return partialHTML |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment