Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render HTML tags sent as Node JS variable in EJS?

Disclaimer: I asked this question when I was clearly a noob, but I am leaving this up hoping it can help someone in the future.

Context: Image to make the question more clear: My issue

I'm working on a Node JS + EJS blog application. I have a separate page(www.domain/compose) where I can write the title and the body for my post. I can then access this post through www.domain/posts/post-title

Like shown in the picture, I want to send over HTML tags that can be rendered.

I want to send any HTML tags to my liking in whatever order I want. Not only the em and img tags.

My Node Server code:

app.post("/compose", (req, res)=>{
  const post = {
    'title': req.body.newPostTitle,
    'body': req.body.newPostContent,
  };
  posts.push(post);
  res.redirect('/');
});

app.get("/posts/:postName", (req, res)=>{
  const urlSuffix = req.params.postName;
  posts.forEach((post)=>{
    const postURL = lodash.kebabCase(post.title);
    if(urlSuffix===postURL || urlSuffix===post.title){
      console.log("Match Found!");
      res.render("post", {postTitle:post.title, postBody: post.body});
      }else{
        console.log("Not a match")
      }
  });
});

My EJS Template code:

<%- include('partials/header') -%>

<h1><%=postTitle%></h1>
<p><%=postBody%></p>

<%- include('partials/footer') -%>
like image 504
Mukul Aryal Avatar asked Jan 17 '26 12:01

Mukul Aryal


1 Answers

I figured it out! All I had to do was change my .ejs template from:

<%=postBody%>

to

<%-postBody%>
like image 180
Mukul Aryal Avatar answered Jan 20 '26 04:01

Mukul Aryal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!