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.
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.
Share Improve this question asked Mar 27, 2021 at 3:13 zakzak 893 silver badges12 bronze badges 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. – SuperStormer Commented Mar 27, 2021 at 3:15
3 Answers
Reset to default 16I 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
then find configure HTML language and add line to end of json file
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.
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.