Reputation: 143
Whenever I attempt to set a variable within a script to be equal to an array rendered using ejs I get 'Invalid are unexpected token'.
Here is the snippet:
<script type="text/javascript">
var list = <%= events.slice(0) %>;
</script>
Originally I had it set to:
<script type="text/javascript">
var list = <%= events %>;
</script>
But I receive the same error. I was pretty certain you could render an ejs file that contains script tags and set the ejs variable to a variable within the script tag. Am I wrong?
Events is an array of event models for a calendar.
Upvotes: 5
Views: 1694
Reputation: 2826
You don't need to add script tags. Just put your code in html
Here is a plain example
index.ejs
<script>
//just call the events variable
for(var i = 0; i < events.length; i++){
var myEvent = events[i];
//handle the event
}
//then use the variables outside the script tag after you are done with all the handling
</script>
<ul>
<li><%=myDefinedVariable%></li>
<% var name = "Jake" %>
<li><%=name%></li>
<%for(var i = 0; i < 10; i++){%>
<li><%=name%></li> // puts li in the ul 10 times
<%}%>
</ul>
Upvotes: 0
Reputation: 4778
this is what you are looking for:
<script type="text/javascript">
var list = <%-JSON.stringify(events)%>;
</script>
Upvotes: 6