_foo.mustache.haml templates
-
26-10-2019 - |
Question
I would like to use a single haml/mustache template, like this:
.foo
%h2 {{title}}
That I can render two ways:
1) As a partial and passing a hash:
render :partial => 'foo', :mustache => {:title => 'hello world'}
=>
<div class='foo'><h2>hello world</h2></div>
2) As a partial without a hash for use inside a script tag:
:javascript
render :partial => 'foo'
=>
<script type='text/javascript'>
<div class='foo'><h2>{{title}}</h2></div>
</script>
I've tried various combinations of file names... "_foo.mustache.haml", for example, however rails won't recognize that extension.
Also, I'm using the mustache_template_handler.rb from ryan bates: http://railscasts.com/episodes/295-sharing-mustache-templates
Solution
So, this works -- but it's not real template chaining (is that even possible?!)
module MustacheTemplateHandler
def self.call(template)
haml = "Haml::Engine.new(#{template.source.inspect}).render"
if template.locals.include? :mustache
"Mustache.render(#{haml}, mustache).html_safe"
else
haml.html_safe
end
end
end
ActionView::Template.register_template_handler(:mustache, MustacheTemplateHandler)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow