Rails with Underscore.js Templates

2019-03-08 20:01发布

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?

2条回答
劫难
2楼-- · 2019-03-08 20:24

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>
查看更多
We Are One
3楼-- · 2019-03-08 20:50

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
};
查看更多
登录 后发表回答