Underscore templating: Can't get switch to wor

2019-04-19 03:34发布

问题:

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

Code coming up:

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

回答1:

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>
<% } %>

becomes JavaScript that looks like this:

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

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

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> 
<% } %>

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

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

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


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 %>

but this will:

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

The same applies to loops.



回答2:

You can do:

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

It isn't a "comfortable" solution, but neither is wrong. Just works.