Search code examples
node.jsejs

Ejs syntax error with object keys that include multiple spaces or special characters longer than 19 characters


I am using a loop to generate sliders in my app using ejs templates. The object passed to this screen has spaces in its keys so I am using bracket notation to get the required values to parse to the slider. The code below works for any sting except for strings that have multiple spaces or special characters where the strings have more 20 or more characters.

Examples of strings that work ("Band", "Primary Technique", "Reel Spool Material")

Examples of strings that fail ("Anti-reverse Feature", "Reel Handle Position")

The code below works with "Primary Technique".

<!DOCTYPE html>
<html lang="en">
  <%- include('layouts/header') -%> <%- include('layouts/navigation') -%>
  <body>
    <%- include('layouts/filterTable') %> <% data.forEach(function(data) { %>
    <div>
      <%-include('layouts/slider', {title: data.Specs[0]["Primary Technique"],
      images: data.Images});-%>
    </div>
    <%})%>
  </body>
  <%- include('layouts/footer'); -%>
</html>

If I change "Primary Technique" to "Reel Handle Position" and save the code, vscode places part of the code on a new line and highlights the function brackets the e at the end of handle in red.

<!DOCTYPE html>
<html lang="en">
  <%- include('layouts/header') -%> <%- include('layouts/navigation') -%>
  <body>
    <%- include('layouts/filterTable') %> <% data.forEach(function(data) { %>
    <div>
      <%-include('layouts/slider', {title: data.Specs[0]["Reel Handle
      Position"], images: data.Images});-%>
    </div>
    <%})%>
  </body>
  <%- include('layouts/footer'); -%>
</html>

I then get a syntax error.

SyntaxError: Invalid or unexpected token in D:\Dave\repos\rodsandreels\views\index.ejs while compiling ejs

I have done a lot of searching on the net trying to see if the phrases contain reserved words. I have looked to see if I need to escape some special characters. I have tried to concatenate portions of the strings.

Is there a way around this constraint without replacing all the spaces in the objects key name?


Solution

  • The issue is due to vs code formatting your ejs file probably via prettier. Try stopping the prettier and removing the line break (If prettier/formatting is stopped it will not move to the next line when saving as you mentioned).