'How to use nunjucks to render a template with data from within a ReactJS app

I am trying to use Nunjucks within a ReactJS app.... I am not even entirely sure this is doable, and so was trying it out.

This is what I am trying at the moment: I have a React web app that accepts user input via a web form. I use this data to fill in a template with nunjucks.

I have a button which when clicked, invokes:

  handleButtonClick() {
    var nunjucks = require("nunjucks")

    console.log(nunjucks.render(
        "template.njk", {
            page_title: "My Title"
        }
    ));
  }

This does produce an HTML output on the browser console.... BUT it does not correspond to what is expected. It basically prints out the source code of public/index.html... a standard file in ReactJS apps. The more surprising part is that even when I specify a non-existent file (e.g. template12345.njk instead of template.njk above), it doesn't produce any error, but rather produces the very same output as before.

Can someone tell me if my approach is altogether incorrect? Is it possible to use nunjucks within a react app? Any leads would be super helpful.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source