Home » Nodejs » Simplest possible node.js + nunjucks example

Simplest possible node.js + nunjucks example

Posted by: admin November 29, 2017 Leave a comment

Questions:

Probably will never use node.js nor Nunjucks for any real development, but now for some reason need:

  • precompile the some simple templates to javascript with Nunjucks
  • run the precompiled templates under the node.js

I have done:

  • installed node.js and the npm (e.g. have node and the npm command)
  • mkdir njtest && cd njtest
  • installed the nunjucks with the npm install nunjucks (got a node_modules/nunjucks directory)
  • mkdir templates
  • in the templates i have created two files index.html and layout.html with the following jinja2/nunjucks content

  • layout.html

<!doctype html>
<head>
        <title>simple example</title>
</head>
<body>
        <h1>Simple example</h1>
        {% block body %}{% endblock %}
</body>
  • index.html
{% extends "layout.html" %}

{% block body %}
hello world
{% endblock %}
  • I precomplied the templates with the
./node_modules/nunjucks/bin/precompile templates >templates.js

and in the templates.js I have the precompiled code.

What I should to do next to get an running web-server what will use the precompiled template.js?

Please, don’t search anything advanced behing this question. This is probably an stupid-simple question for someone who know node and javascript.

What i know, will need, create a file let says app.js and need run it with the node – but what should contain?

require 'nunjucks';

and probably something like: var res = nunjucks.render('templates.js'); and what else? (the simplest possible (one time) solution). Note: want use Nunjucks server-side and not in the browser.

Answers:

Start by initialising your Node application as follows:

cd njtest
npm init

You can hit “Enter” to accept the defaults for most of the questions, if you’re doing this after creating app.js then it’ll automatically detect this and use it as the entry point for your simple server.

Install Express:

npm install express --save

Then create app.js as follows:

var express     = require( 'express' ),
    app         = express(),
    nunjucks    = require( 'nunjucks' ) ;

// Define port to run server on
var port = process.env.PORT || 9000 ;

// Configure Nunjucks
var _templates = process.env.NODE_PATH ? process.env.NODE_PATH + '/templates' : 'templates' ;
nunjucks.configure( _templates, {
    autoescape: true,
    cache: false,
    express: app
} ) ;
// Set Nunjucks as rendering engine for pages with .html suffix
app.engine( 'html', nunjucks.render ) ;
app.set( 'view engine', 'html' ) ;

// Respond to all GET requests by rendering relevant page using Nunjucks
app.get( '/:page', function( req, res ) {
    res.render( req.params.page ) ;
} ) ;

// Start server
app.listen( port ) ;
console.log( 'Listening on port %s...', port ) ;

Now fire up a browser, go to http://localhost:9000 and up pops your page!

Hope that helps…