admin管理员组

文章数量:1414865

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

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?

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/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?

Share Improve this question edited Aug 7, 2014 at 11:05 Mazhar Ahmed asked Aug 7, 2014 at 7:54 Mazhar AhmedMazhar Ahmed 1,5433 gold badges24 silver badges41 bronze badges 3
  • you want to use the partial function in EJS. – haxxxton Commented Aug 7, 2014 at 7:57
  • Can you please describe a bit more? Because I've already used partial but that's not the issue. It's about the values are getting converted into html entities on the fly I pass them to ejs. How to prevent it? – Mazhar Ahmed Commented Aug 7, 2014 at 9:56
  • it would be nice to share the solution with us tho: <%-b%> – Raqun Bob Commented Nov 1, 2020 at 0:29
Add a ment  | 

2 Answers 2

Reset to default 5

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.

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;');
  }
});

本文标签: javascriptPassing html tags as ejs variables39 valueStack Overflow