Search code examples
backbone.jsunderscore.jsmustache

How do i if/then in "mustache"-like underscore.js?


I use underscore.js for HTML Templating, set to use mustache syntax, like this: {{ }}

I have this code:

 <% if (typeof(date) != "undefined") { %>
  <span class="date"><%= date %></span>
 <% } %>

How can I translate it to an underscore.js mustache-style template, using {{ }}?


Solution

  • I use:

        _.templateSettings = {
          evaluate : /\{\[([\s\S]+?)\]\}/g,
          interpolate : /\{\{([\s\S]+?)\}\}/g
        };
    

    Then instead of <%= … %> use {{ … }} and instead of <% … %> use {[ … ]}