writing ejs in a script is giving me the error 'Expression expected'
Asked Answered
N

3

9

I have a script tag in my show.ejs file, and I have the following line:

<script>
    const post = <%- JSON.stringify(post) %>
</script>

I'm getting the error of 'Error Expected' on both the opening and closing ejs tags. I was wondering why this error occurs and if there was anything I'm doing that isn't allowed.

Nadia answered 27/3, 2021 at 3:13 Comment(1)
Are you sure your ejs file is being interpreted as ejs and not a normal html file? Please post the relevant parts of your server code.Universality
F
16

I just have same issue with VS code if you using VS you need to add to end of settings.json in cofiguration of html this line

"html.validate.scripts": false,

find html in bottom right find html in bottom right

then find configure HTML language then find configure HTML language and add line to end of json file and add line to end of json file

Falconer answered 10/4, 2021 at 17:12 Comment(1)
Seems to be the best workaround currently, see: related github issue. I put it in the workspace settings file .vscode/settings.json so I retain the functionality in other projects.Dunois
C
2

There are 2 optional ways.

1)

Change the global delimiters of EJS.

const ejs = require("ejs");

ejs.delimiter = '/';
ejs.openDelimiter = '[';
ejs.closeDelimiter = ']';

Update your script.

<script>
const post= [/- JSON.stringify(post) /];
</script>

2)

Add this property to settings.json in VSCode.

"html.validate.scripts": false

Change the global delimiters of EJS.

const ejs = require("ejs");

ejs.delimiter = '?';
ejs.openDelimiter = '[';
ejs.closeDelimiter = ']';

Update your script.

<script>
const post= [?- JSON.stringify(post) ?];
</script>

Note: Auto format will work correctly in 2 ways.

Note: I prefer the first one because I can use both auto format and scripts validation and I don't need any EJS extension.

Carbamate answered 18/2, 2022 at 20:27 Comment(0)
K
0

This is the answer that worked for me after 2 days of searching and finding nothing.

As for some reason that syntax inside script does not work properly, what you can do is use a data attribute inside html part of the ejs file.

<div id="postData" post="<%= post%>"></div>

And then get the value inside script part of the code.

<script> const post= document.getElementById('postData').getAttribute('post'); </script>

Hope this helps, I guess in this way it works as intended, at least it did for me.

Kosse answered 27/6 at 22:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.