Meaning of escaped and unescaped value in context of ejs templating engine?

Viewed 1365

<%= Outputs the value into the template (HTML escaped) <%- Outputs the unescaped value into the template

What these 2 lines means specifically the 'escaped' and 'unescaped' word?

1 Answers

Let me show you a simple example.

Let's say you have data stored in your database and want to render it in a view ejs page. Example:

x = "<p>This is a paragraph</p>"

Now add the these lines in your ejs page

<%= x %>
<%- x %>

You are going to see this

<p>This is a paragraph</p> 
This is a paragraph

As you see, <%= tag escapes the html tags, and does not let them to be translated.
The opposite happens with <%- tag, where html is translated (unescaped), and you see the result you wish.

<%= tag escapes that code for security reasons. In case you want to use <%- tag you have to be sure about the data you store on your database and want later render them.

Think about this data

x = "<script>alert('You are in danger!')</script>"

And try to render it this way

<%- x %>

Guess what! You are going to see a nice alert message informing you that if you aren't sure about your data, you are in danger.

Hope I helped you.

Related