Search code examples
javascriptunderscore.jslodashtemplate-engine

Printing variables within Underscore template ternary


Is it possible to print a variable in an underscore template during an evaluation like.

<a href="<%=data.active ? 'the/url' : 'another/url/<%='data.id'%>'%>">Link with printed parameter</a>

This gives me an Unexpected identifier error. I've tried with various excapings around the second %> but it just prints literally. I've also tried using the print() alias so that the compiler doesn't get confused by the repeating %>, however no luck. Is there a way to do this within a ternary?


Solution

  • Works without problems when you don't try do use nested the templates.

    var source = document.getElementById("testTemplate").innerHTML;
    var testTemplate = _.template(source);
    
    document.getElementById("target1").innerHTML = testTemplate({
      data: {
        active: false,
        id: 12345
      }
    });
    
    document.getElementById("target2").innerHTML = testTemplate({
      data: {
        active: true,
        id: 67890
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    
    <script type="text/template" id="testTemplate">
      <a href="<%= data.active ? 'the/url' : 'another/url/' + encodeURIComponent(data.id) %>">Link with printed parameter</a>
      <p>The URL is "<%= data.active ? 'the/url' : 'another/url/' + encodeURIComponent(data.id) %>".</p>
      <hr>
    </script>
    
    <div id="target1"></div>
    <div id="target2"></div>

    Note: Even if your data.id normally is strictly numeric, it's better to just use encodeURIComponent anyway when you are building a URL. Escaping data cleanly is a good habit to get into.