Search code examples
javascriptbackbone.jsunderscore.jsunderscore.js-templating

Outputting directly to template with Embedded Javascript Syntax


I'm using Backbone with Underscore templates. I have a JavaScript if() condition in my code that looks something like this:

<div class='faces'>
    <% if(somevalue === true) { %>
       your face
    <% } else { %>
       my face
    <% } %>
</div>

However I find this syntax awkward and I really would like to use something like the following, even though it doesn't actually work (replaces entire document with the text):

<div class='faces'>
    <% if(somevalue === true) { 
        document.write("your face");
    } else { 
        document.write("my face");
    }
</div>

I want the string to be output in the template exactly where it is called. For outputting a simple variable EJS (and underscore) have a great syntax of

<%= somevalue %>

Where the = is the critical part that document.write()s it out into the template. Is what I'm trying to accomplish possible? Can JavaScript output inline?


Solution

  • There are a few options, you could use <%= %> and a ternary:

    <%= somevalue == true ? 'your face' : 'my face' %>
    

    or you could use print:

    You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.

    var compiled = _.template("<% print('Hello ' + epithet); %>");
    compiled({epithet: "stooge"});
    => "Hello stooge."
    

    so you could do this:

    <% if(somevalue == true) { 
        print("your face");
    } else { 
        print("my face");
    } %>
    

    I'm assuming that if(somevalue = true) is a typo and should be if(somevalue == true).