Mazhar Ahmed
Mazhar Ahmed

Reputation: 1533

Passing html tags as ejs variables' value

I'm using Koa Framework and EJS templates to render the views. I need to send some html element values to the view. But the ejs library is converting them to html entities. I'm following how they told in https://www.npmjs.org/package/koa-ejs

In my js file:

yield this.render('ejs file name', {
  a: 'hi',
  b: '<a href="hi">hi</a>'
});

My view file:

<%=a %>
<%=b %>

What I'm getting after running the code:

hi
&lt;a href="hi"&gt;hi&lt;/a&gt;

But I need <a href="hi">hi</a> as value not &lt;a href="hi"&gt;hi&lt;/a&gt;

Does anyone have any suggestion how to to that?

Upvotes: 1

Views: 4408

Answers (2)

Vicheans
Vicheans

Reputation: 111

To deal with EJS and Node JS using a text-editor(i use tinyMCE though) just call the tag into this <%- <YOUR-VARAIABLE-NAME> %>, that strips all the tags and render your texts perfectly.

Upvotes: 5

Mazhar Ahmed
Mazhar Ahmed

Reputation: 1533

Found the solution by manually inspecting the module's code. By default the ejs module will escape the values. To prevent it we need to send our own escape function to the module which will overwrite the existing.

yield this.render('ejs file name', {
  a: 'hi',
  b: '<a href="hi">hi</a>',
  escape: function(html) {
    return String(html);
    // don't replace the htmls
    //.replace(/&/g, '&amp;')
    //.replace(/</g, '&lt;')
    //.replace(/>/g, '&gt;')
    //.replace(/'/g, '&#39;')
    //.replace(/"/g, '&quot;');
  }
});

Upvotes: 1

Related Questions