How to render html code stored as string?

Viewed 101

Hi I am trying to send the contents of string stored in mongo db through res.render. However, if I check after sending this string, the tag appears in the form of a string and does not appear in html, so I want to know how to solve it.

 router.get("/:id", async function (req, res) {
  var article = await Article.findById(req.params.id); 
  console.log(article);
  res.setHeader("Content-type", "text/html");
  res.render("articles/article", { article: article });
});

article = "<p>내용입니다.</p>"

enter image description here

1 Answers

here is the working example. You have to install the pug template engine or any other template engine. See the test. pug file and note that if the variable is HTML content then we have to use the syntax "!{para}" or if the variable is a simple string then we can use the syntax "#{para}".

so the folder structure would be like

app.js views ->test.pug

// app.js file
var express = require('express');
var app = express();
var PORT = 3000;
app.set('view engine', 'pug');
app.use('/', function(req, res, next){
    res.render('test', {para : `<p>This is paragraph</p>`});
});
  
app.listen(PORT, function(err){
    if (err) console.log(err);
    console.log("Server listening on PORT", PORT);
});

// html file test.pug

<div>!{para}</div>
Related