Outputting directly to template with Embedded Java

2019-08-13 18:03发布

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?

1条回答
▲ chillily
2楼-- · 2019-08-13 19:00

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).

查看更多
登录 后发表回答