3

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

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> Commented Jan 18, 2016 at 15:10
  • I will have different kind of messages: 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 Commented Jan 18, 2016 at 15:28

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.