Search code examples
node.jsif-statementejsscriptlet

ejs How do I get if-then-else behavior in scriptlet


In generating HTML with node.js EJS I'm not able to use an "else if" if my scriptlet tags look like:

 <% var qtype; %>
 <% if (qobj.ansType == 1) { %>
 <% qtype = 'multiChoice'; %>
 <% } %>
 <% else if (qobj.ansType == 0) { %>
 <% qtype = 'shortAnswer'; %>
 <% } %>
 <% else { %>
 <% qtype = 'longAnswer'; %>
 <% } %>

 Type:<%- select_tag("type",
    [{"value": 'multiChoice',"text": "Multiple Choice"},
    {"value": 'shortAnswer',"text": "Short Answer"},
    {"value": "longAnswer","text": "Text Answer"}],
    {"value": qtype}) %>   //  qtype should be set based on if-else statements above

I get: Unexpected else token in question.ejs while compiling ejs

I'm trying to get the default item in the select pulldown to be conditional based on the value of qobj.ansType. It should be set to multiChoice if qobj.ansType = 1 and shortAnswer if qobj.ansType = 0 .

Doc for EJS says I can use full javascript in scriptlets but it looks like else if isn't allowed so is it full javascript or not? I'd prefer not doing 3 ifs in a row.


Solution

  • You need to add the else statements immediately after the closing braces of an if statement. You can't have else or else if on its own line by itself.

    Try:

     <% var qtype; %>
     <% if (qobj.ansType == 1) { %>
     <% qtype = 'multiChoice'; %>
     <% } else if (qobj.ansType == 0) { %>
     <% qtype = 'shortAnswer'; %>
     <% } else { %>
     <% qtype = 'longAnswer'; %>
     <% } %>