如果检查变量,则下划线js模板

use*_*019 0 templates backbone.js underscore.js web

我试图使用underscore.js模板方法来渲染一些数据,所以基本上这是我想要做的,如果我在伪代码中做

if (url is not null) {
     <div>
       <img src=url />
     </div>
}
Run Code Online (Sandbox Code Playgroud)

我需要在下划线js模板中执行此检查,但我不确定以下是否合法,棘手的部分是url也是模板变量

<% if (<%=url%>) { %>
    <img src=<%=url%> />
<% } %>
Run Code Online (Sandbox Code Playgroud)

救命?

Raf*_*tta 5

在javascript上:

 var myTmpl = _.template(foo);
 myTmpl.tmpl({url: 'foo.com'});
Run Code Online (Sandbox Code Playgroud)

在模板上:

<% if (url) { %>
  <img src=<%=url%> />
<% } %>
Run Code Online (Sandbox Code Playgroud)

记住:当你使用<%时,你只是在写javascript;)