22

I was trying to use underscore.js templates for templating in a rails 2.3 app which does not have jammit as an asset packager.

Here is the simple Template:

<script type="text/template" id="q-template">
    <div class="current-body">
        <span class="q-index"><%= title %></span>
        <span class-"q-text"><%= body %></span>
    </div>
</script>

Rails tries to parse these as erb variables and throws an ArgumentError. How do I get underscore templates to play nicely with rails in this case? Where am I going wrong?

paddle42380
  • 6,921
  • 7
  • 32
  • 40

2 Answers2

52

Use some other delimiters instead of <%= %>. For example, to use mustache-style brackets {{= }} (interpolate) and {{ }} (evaluate), add this somewhere to your javascript:

_.templateSettings = {
    interpolate: /\{\{\=(.+?)\}\}/g,
    evaluate: /\{\{(.+?)\}\}/g
};
Eric C
  • 3,886
  • 3
  • 30
  • 26
kulesa
  • 2,964
  • 20
  • 11
  • Thanks, this works. I was going through the documentation for _.template and _.templateSettings was mentioned there, but somehow it skipped my mind when i was setting up the project, and kept thinking this could be jammit related. – paddle42380 Sep 22 '11 at 13:35
  • 3
    Thanks FYI : http://documentcloud.github.com/underscore/#template and http://stackoverflow.com/questions/5771742/underscore-js-templates-within-jsp – Francois Jan 04 '12 at 15:52
  • 6
    Using `{{ }}` and `{{= }}` can cause problems if you want use `if (x) {}` style blocks in your templates. It's probably easier in that case to use `[% %]` and `[%= %]` instead: – Ash Berlin-Taylor Aug 20 '12 at 11:36
  • Another option that doesn't require global replace is to specify the interpolate and evaluate to specific method invocation `_.template($("#q-template").html(),null, { interpolate : /\{\{\=(.+?)\}\}/g, evaluate: /\{\{(.+?)\}\}/g });` – katzmopolitan Jul 04 '15 at 03:15
27

If you don't want to change the template settings across your entire project...

Escape the ERB tags: <%= becomes <%%=

<script type="text/template" id="q-template">
    <div class="current-body">
        <span class="q-index"><%%= title %></span>
        <span class-"q-text"><%%= body %></span>
    </div>
</script>

Note that the closing tag is still %>, not %%>.


Side note - I also tried outputting using a heredoc. The following code runs successfully but outputs a bunch of erb source code that gets caught between the heredoc commands.

<script type="text/template" id="q-template">
<%= <<-heredoc %>
    <div class="current-body">
        <span class="q-index"><%%= title %></span>
        <span class-"q-text"><%%= body %></span>
    </div>
heredoc
</script>
colllin
  • 9,442
  • 9
  • 49
  • 65