Skip to content

Instantly share code, notes, and snippets.

@zznq
Created January 8, 2014 20:50
Show Gist options
  • Save zznq/8324394 to your computer and use it in GitHub Desktop.
Save zznq/8324394 to your computer and use it in GitHub Desktop.
Some code snippets to help guide in using mustache templates for both client side rendering and server side rendering(in rails)
<section class="{{type}}>
<p>{{body}}</p>
{{#some_partial}}
</section>
<div class="{{type_2}}">
<ul>
{{#somethings}}
<li>{{thing}}</li>
{{/somethings}}
</ul>
</div>
define([
'mustache',
'text!templates/things/_details.mustache',
'text!templates/shared/_some_partial.mustache'
], function(Mustache, template, partial) {
//initialize, wait for dom, ect.
var some_model = { type: '1', body: 'hello', somethings: [{thing: 1},{thing:2}]};
var t = Mustache.compile(template);
// something like that, my app is much more complicated then this example
$(body).append(t.render({ some_model}, { some_partial: partial }))
}
#config/initializers
class MustacheWithPartial < Mustache
self.template_path = 'app/assets/templates/'
def render(data=template, ctx={})
@ctx = ctx
super
end
def partial(name)
if @ctx.has_key? name
name = @ctx[name]
file_path = "#{template_path}/#{name}.#{template_extension}"
if File.exists? file_path
return File.read(file_path)
end
end
super
end
end
module MustacheTemplateHandler
def self.call(template)
if template.locals.include? 'mustache'
"MustacheWithPartial.render(#{template.source.inspect}, mustache).html_safe"
else
"#{template.source.inspect}.html_safe"
end
end
end
ActionView::Template.register_template_handler(:mustache, MustacheTemplateHandler)
#class-details.item-wrapper.class
= render '../assets/templates/things/details', :mustache => { :model => @klass, :some_partial => 'shared/_some_partial' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment