I am following a tutorial about node.js and mongodb featuring ejs templates. I have this ejs template which uses a javascript function to output a list. This list includes html tags. But it doesnt interpret these html tags and just shows them as text.
Link to the tutorial: https://closebrace.com/tutorials/2017-03-02/the-dead-simple-step-by-step-guide-for-front-end-developers-to-getting-up-and-running-with-nodejs-express-and-mongodb
Here is the line from the code that causes the problem
<h1>User List</h1>
<ul>
<%
var list = '';
for (i = 0; i < userlist.length; i++) {
list += '<li><a href="mailto:' + userlist[i].email + '"></a>' + userlist[i].username + '</a></li>';
}
%>
<%= list %>
</ul>
I appreciate your support!
I think it is an error in the tutorial. When you add you the
list
variable, you are putting HTML elements into a string.Ejs will automatically escape these when you do
<%= list %>
.To get the string to be interpreted as HTML you have to change it to
<%- list %>
.Having said this, you need to be very careful when using this, as it potentially leaves the website open to people injecting scripts into your page (XSS).
You would be better off doing something like this: