问题
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:
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
<%= ... %>
.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)
.
来源:https://stackoverflow.com/questions/8766882/outputting-directly-to-template-with-embedded-javascript-syntax