javascript - Passing html tags as ejs variables' value - Stack Overflow

I'm using Koa Framework and EJS templates to render the views. I need to send some html element va

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745224006a4617378.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信