How to evaluate javascript functions in underscore with mustache notation?

爱⌒轻易说出口 提交于 2019-12-22 17:59:10

问题


I want to do something like this:

<script id="tmpl-books" type="text/template">
  <ul>
    <% for (var i = 0; i < books.length; i++) { %>
      <% var book = books[i]; %>
      <li>
      <em><%= book.title %></em> by <%= book.author %>
      </li>
    <% } %>
  </ul>
</script>

in my code, but I am using JSP so I have to use the {{ }} notation, but when I do this {{ for(var... }} does not work.

<script id="tmpl-books" type="text/template">
      <ul>
        {{ for (var i = 0; i < books.length; i++) { }}
          <% var book = books[i]; %>
          <li>
          <em>{{= book.title }}</em> by {{ book.author }}
          </li>
        {{ } }}
      </ul>
    </script>

How can I achieve this?


回答1:


Underscore templates have three distinct regexes:

Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string.

If you want to use Handlebars-ish delimiters, you'll want to define all three rather than just the interpolate regex:

_.templateSettings = {
    evaluate: /\{\{(.+?)\}\}/g,
    interpolate: /\{\{=(.+?)\}\}/g,
    escape: /\{\{-(.+?)\}\}/g
};

Also note that the interpolate and escape regexes must match things that evaluate won't due to the order that the regexes are applied in.

With those template settings, a template like this:

<script id="tmpl-books" type="text/template">
    <ul>
        {{ for (var i = 0; i < books.length; i++) { }}
            {{ var book = books[i]; }}
            <li>
                <em>{{= book.title }}</em> by {{= book.author }}
           </li>
        {{ } }}
    </ul>
</script>

should work. Note the change from {{ book.author }} to {{= book.author }} since you're interpolating book.author, not evaluating it.



来源:https://stackoverflow.com/questions/21640236/how-to-evaluate-javascript-functions-in-underscore-with-mustache-notation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!