0

I'm writing a shell script, and would like to use template it, by keeping my variables in a json file.

I'm a beginner to javascript, and so can't seem to get the hang of how to use nunjucks to render my templates. Can you please help me get this simple example to work?

Here's my current attempt. (I have npm installed)

In my project directory :

$ npm install nunjucks

I create sample.njk with the following contents :

{{ data }}

And index.js with the following content :

var nunjucks = require('nunjucks')
nunjucks.configure({ autoescape: true });
nunjucks.render('sample.njk', { data: 'James' });

My project directory then, looks like :

index.js  node_modules/  sample.njk

I run index.js with node as

$ node index.js

How do I get it to output (to the command line, or to a new file):

James

after processing the template?

I've tried looking at gulp-nunjucks and gulp-nujucks-render, but there's too much going on there, and I can't even get a simple task accomplished here.

When I define my data in a json file, I only need pass it as a context in the nunjucks.render() function, right?

Thanks for your help.

lip
  • 114
  • 1
  • 11
  • 1
    The nunjucks.render probably returns rendered string so just use `var data = nunjucks.render(...);` and `console.log(data);` or `fs.writeFile('/path/to/file.html', data, function(){})` – Molda May 02 '16 at 04:26

1 Answers1

2

Depends on what you're trying to accomplish with the data outputted by the Nunj render. If you simply want to print it to the terminal, a simple console.log(); will work.

In Express, res.render takes an optional third param which is a fn. You would do it as such:

var nunjucks = require('nunjucks');
nunjucks.configure({ autoescape: true });
nunjucks.render('sample.njk', { data: 'James' }, function (err, output) {

    // If there's an error during rendering, early return w/o further processing
    if (err) {
        return;
    }

    // The render fn calls the passed-in fn with output as a string
    // You can do whatever you'd like with that string here
    console.log(output);

});
SC_Chupacabra
  • 12,907
  • 1
  • 15
  • 21