最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass html tags in a string with node.js, express and ejs - Stack Overflow

programmeradmin1浏览0评论

I use Node.js with Express and EJS and I want to pass html tags in a string to the browser like this:

listRequests.forEach(function(key) {
    messages.push("You have a message from <b>" + key.username + "</b>");
});

Later in my code:

res.render('/wallets', {
              messages     : messages,
              ...
           });

And in my html template, I have something like

<h2>Messages</h2>
<% messages.forEach(function(message) { %>
<p><%= message %></p>
<% }); %>

The problem: the browser displays the text with the tags like <b>John</b> instead of John

I use Node.js with Express and EJS and I want to pass html tags in a string to the browser like this:

listRequests.forEach(function(key) {
    messages.push("You have a message from <b>" + key.username + "</b>");
});

Later in my code:

res.render('/wallets', {
              messages     : messages,
              ...
           });

And in my html template, I have something like

<h2>Messages</h2>
<% messages.forEach(function(message) { %>
<p><%= message %></p>
<% }); %>

The problem: the browser displays the text with the tags like <b>John</b> instead of John

Share Improve this question asked Jan 18, 2016 at 15:07 jfjobidonjfjobidon 3275 silver badges18 bronze badges 3
  • 1 Split it into two attributes. Text and name. Like this { text: " You have a message from", username: "John"}. Then just use the two attributes in the template. <p><%= message.text %> <b><%= message.username %> </b></p> – magnudae Commented Jan 18, 2016 at 15:10
  • I will have different kind of messages: – jfjobidon Commented Jan 18, 2016 at 15:20
  • you have a new <a href="linkToMessage">message</a> from <b>user111<b> You have a <a href="linkToRequest">request</a> to access your wallet The wallet <a href="linkToWallet">ABC</a> will needs more funds that's why I would like to construct the text before sending it to the template – jfjobidon Commented Jan 18, 2016 at 15:28
Add a ment  | 

1 Answer 1

Reset to default 6

To render raw html with ejs, use <%- your_var %>. In your case:

<h2>Messages</h2>
<% messages.forEach(function(message) { %>
<p><%- message %></p>
<% }); %>

It's the same to render partial views.. etc.. give it a try

发布评论

评论列表(0)

  1. 暂无评论