直接输出到模板,嵌入的JavaScript语法 [英] Outputting directly to template with Embedded Javascript Syntax

查看:119
本文介绍了直接输出到模板,嵌入的JavaScript语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的骨干以下划线的模板。我有一个JavaScript在我的code 如果()条件看起来是这样的:

 < D​​IV CLASS ='面对'>
    <如果%(someValue中===真){%GT;
       你的脸
    <%}其他{%GT;
       我的脸
    <%}%GT;
< / DIV>

不过,我觉得这种语法尴尬,我真的想使用类似以下,即使它实际上并没有工作(替换整个文档的文字):

 < D​​IV CLASS ='面对'>
    <如果%(someValue中===真){
        文件撰写(你的脸);
    }其他{
        文件撰写(我的脸);
    }
< / DIV>

我希望字符串在模板正是它被称为输出。输出一个简单的变量EJS(和下划线)有很大的语法

 <%= someValue中%GT;

= 是关键的一部分的document.write()的IT外面的模板。就是我要完成的可能吗?也可以javascript输出直列?


解决方案

有几个选项,你可以使用<%=%> 和三元:

 <%= someValue中==是真的吗? 你的脸:我的脸'%GT;

或者你可以使用 打印


  

您也可以JavaScript的code中使用打印从。这有时比使用更方便<%= ...%方式>

  VAR编译= _.template(<%的打印('你好'+形容词);%GT;);
编译({绰号:跟屁虫});
= GT; 你好跟屁虫。


所以你可以这样做:

 <若%(someValue中==真){
    打印(你的脸);
}其他{
    打印(我的脸);
}%GT;

我假设如果(someValue中= TRUE)是一个错字,应该如果(someValue中== true)而

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?

解决方案

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

这篇关于直接输出到模板,嵌入的JavaScript语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆