Search code examples
javascriptnode.jsejsblogs

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') -%>

Solution

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

    <%=postBody%>
    

    to

    <%-postBody%>