下划线模板:无法切换工作 [英] Underscore templating: Can't get switch to work

查看:109
本文介绍了下划线模板:无法切换工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的下划线模板中没有一个简单的switch语句.它使用一个名为UserType的变量的值,通过用<%= UserType%>显示它来检查它是否存在.

I can't get a simple switch statement working in my underscore template. It's using the value of a variable called UserType which I've checked exists by displaying it with <%= UserType %>.

代码即将发布

<% switch(UserType) { %>
    <% case 13: %>
        <button id="schoolButton" value="schools" class="gridChooser k-textbox">Schools</button> 
    <% case 12: %>
        <button id="teacherButton" value="teachers" class="gridChooser k-textbox">Teacher</button> 
    <% case 8: %>
        <button id="classButton" value="classes" class="gridChooser k-textbox">Classes</button> 
        <button id="testButton" value="tests" class="gridChooser k-textbox">Test</button> 
<% } %>

非常感谢您的帮助-谢谢.

Any help much appreciated - thanks.

推荐答案

问题在于,在将模板转换为JavaScript时,Underscore会添加分号终止符.因此,像这样的简单switch:

The problem is that Underscore will add semicolon terminators when converting your template to JavaScript. So, a simple switch like this:

<% switch(x) { %>
<% case 11: %>
    <button>
<% } %>

成为看起来像这样的JavaScript:

becomes JavaScript that looks like this:

switch(x) { ;
case 11: ;
    // something to output '<button>' goes here
} ;

但是JavaScript switch 需要包含case语句,并且空语句(即switch(x) { ;中的;)不符合条件.

But a JavaScript switch needs to contain case statements and an empty statement (i.e. the ; in switch(x) { ;) doesn't qualify.

我想不出解决此问题的任何明智方法,因此我只想切换到if并继续处理更有趣的问题:

I can't think of any sane way around this problem so I'd just switch to an if and move on to more interesting problems:

<% if(UserType === 13) { %>
    <button id="schoolButton" value="schools" class="gridChooser k-textbox">Schools</button> 
<% } else if(UserType === 12) { %>
    <button id="teacherButton" value="teachers" class="gridChooser k-textbox">Teacher</button> 
<% } else if(UserType === 8) { %>
    <button id="classButton" value="classes" class="gridChooser k-textbox">Classes</button> 
    <button id="testButton" value="tests" class="gridChooser k-textbox">Test</button> 
<% } %>

您也可以将其内翻并使用print:

You could also turn it inside-out and use print:

<% switch(UserType) {
   case 13:
       print('<button id="schoolButton" ...');
   ...
} %>

但是有点丑陋(恕我直言).有关详细信息,请参见 _.template文档.

but that's a bit ugly (IMHO). See the _.template documentation for details.

请注意,这种分号技巧也是为什么您的if必须在Underscore模板中包含括号的原因,即使JavaScript不需要括号也是如此.所以这行不通:

Note that this semicolon trickery is also why your ifs must include braces in an Underscore template even if JavaScript doesn't require them. So this won't work:

<% if(pancakes) %>
    <%= pancakes %>

但这会:

<% if(pancakes) { %>
    <%= pancakes %>
<% } %>

循环同样如此.

这篇关于下划线模板:无法切换工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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