Skip to content
danmacpherson edited this page Feb 7, 2013 · 1 revision

Mustache templates

We are using Mustache templates for the partials which are initially rendered by Rails and then autoupdated by Backbone periodically. These needs to be rendered by both Rails and Javascript. How do we to this is inspired by a Railscasts episode [1].

Our Mustache templates are not purely Mustache templates but some hybrid ERB-Mustache templates. The purpose of this is to be able to use Rails helper methods like I18n. It means that the template is first compiled by ERB template handler. Then, if the data for the partial has been passed through the :mustache option, it is also compiled by Mustache. You can find the Mustache template handler in: config/initializers/mustache_template_handler.rb

To have the same representation of data both for the rendering in Rails and for the JSON response you can create a helper in app/helpers/mustache_helper.rb.

To render the html output of the mustache template:

<code class="ruby">
render :partial => 'mustache_partial', :mustache => data_for_mustache
</code>

To render the raw mustache template for JavaScript:

<code class="ruby">
render :partial => 'mustache_partial'
</code>

In JavaSript you can render the template:

<code class="javascript">
Mustache.to_html($template.html(), data_for_mustache);
</code>

[1] http://railscasts.com/episodes/295-sharing-mustache-templates

[2] Mustache source: http://mustache.github.com/

Clone this wiki locally