Search code examples
htmlnode.jssyntax-errorejs

I fixed a weird syntax error with ejs, and I'm wondering what the issue was


I'm building a blog webpage as a personal project as a way to learn web development, and I came across this strange syntax error. I modified my code so that logged in and logged out users would get a different navigation bar. The following code caused an error:

<% if(firstp==="Welcome"){%>
        <%-include('./partials/nav2.ejs')%>
    <%}%>
    <%else%>
    <%{ %>
        <%-include('./partials/nav.ejs')%>
    <%  } %>

Logged in users get nav2, while logged out users are sent to the else clause and see nav. Logged out users get the following error:

Unexpected token 'else' in C:\Users\[REDACTED]\browse.ejs while compiling ejs

Logged in users will get the same error, or depending on exactly how I wrote my ejs, will get something like "missing parentheses" (I forgot to copy the error and how exactly to replicate it). The following code works:

<% if(firstp==="Welcome"){%>
        <%-include('./partials/nav2.ejs')%>
    <%}else{ %>
        <%-include('./partials/nav.ejs')%>
    <%  } %>

Both are valid JavaScript syntax, so what gives?


Solution

  • The error is related to how EJS generates the Javascript code for tags, each tag is prefixed with a semi colon;

    The first example amounts to:

    ; if(firstp==="Welcome"){
    ; include('./partials/nav2.ejs')
    ; }
    ; else
    ; {
    ; include('./partials/nav.ejs')
    ; }
    

    The semicolons are used to separate Javascript statements from the previous tag, but in this case the semicolon ends the if statement. In more common JS formatting, this is what's happening:

    if(firstp==="Welcome"){
      include('./partials/nav2.ejs'); 
    };
    else;
    {
      include('./partials/nav.ejs'); 
    }
    

    The working example only injects semicolons inside the if statements curly braces {} which doesn't terminate the if statement

    ; if(firstp==="Welcome"){
    ; include('./partials/nav2.ejs')
    ; } else {
    ; include('./partials/nav.ejs')
    ; }