admin管理员组文章数量:1246474
I am using the _.template()
function of underscorejs together with backbonejs. When using underscore.js v1.3.0, I could use an if
statement as shown:
<script type="text/template" id="tpl_listing_list_item">
<% if(<%= address_2 %>){%>, <%= address_2 %><%}%>
</script>
Problem: After updating to v1.3.3, I get the error Uncaught SyntaxError: Unexpected token ILLEGAL
in the Javascript console. Has this feature been removed? Removing the if
code fixes the error. If it's removed, is there another way to achieve the same thing?
I am using the _.template()
function of underscorejs together with backbonejs. When using underscore.js v1.3.0, I could use an if
statement as shown:
<script type="text/template" id="tpl_listing_list_item">
<% if(<%= address_2 %>){%>, <%= address_2 %><%}%>
</script>
Problem: After updating to v1.3.3, I get the error Uncaught SyntaxError: Unexpected token ILLEGAL
in the Javascript console. Has this feature been removed? Removing the if
code fixes the error. If it's removed, is there another way to achieve the same thing?
2 Answers
Reset to default 8In your if
statement you've already escaped into interpolation mode, so the <%=
is an illegal character.
This works when I use it in my browser with 1.3.3
<script type="text/template" id="tpl_listing_list_item">
<% if(address_2){ %>, <%= address_2 %> <% } %>
</script>
Example:
var t = _.template('{% if(address_2){ %}, {{ address_2 }} {% } %}')
undefined
t({'address_2': 'test'});
", test "
(We use JSP so our template tags are {% %}
, {{ }}
, and {%- %}
instead of the defaults, so excuse my tags)
tkone has it right but for a template like you have, you could use the special print
function to clean up your tags:
You can also use
<%= ... %>
.var piled = _.template("<% print('Hello ' + epithet); %>"); piled({epithet: "stooge"}); => "Hello stooge."
So you could cut down on the noise like this:
<script type="text/template" id="tpl_listing_list_item">
<% if(address_2){ print(', ', address_2) } %>
</script>
Demo: http://jsfiddle/ambiguous/UgATZ/
本文标签: javascriptIf conditional statements in UnderscorejsStack Overflow
版权声明:本文标题:javascript - If conditional statements in Underscore.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740216815a2243019.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论