Search code examples
node.jsnunjucks

NodeJS: How to add a HTML value (taken from a JSON file) on the webpage?


I've some HTML values in a JSON file. I want to display that HTML on my website in text format, not in HTML format.

I'm fetching HTML data from a JSON file and using Nunjuck Template to display it on web page but instead of text format, it get showed up in HTML format like this:

enter image description here

This is the code I'm using:

const JSONFile = require('../public/blog.json');
.
.
.
router.get('/:post', function (req, res) {
        const path = req.params.post;
        const json = JSONFile[path];
        const content2 = json.content;
        res.render('blogs.njk', {
                content: content2,
        });
});

I had even tried using node-html-to-text but later realized that it's mainly for changing email formats which don't work on my blogging site.

What should I do?


Solution

  • Try using the safe-filter in your nunjucks-template.

    {{ content | safe }}
    

    Make sure you are protected against XSS-attacks, which become possible when using the safe-filter. Watch closely where you fetch your HTML from.