Outputting directly to template with Embedded Javascript Syntax

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 12:00:15

问题


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



来源:https://stackoverflow.com/questions/8766882/outputting-directly-to-template-with-embedded-javascript-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!