Page Content

Tutorials

What is the Fastest Template Engine for node JS?

Template Engine for node JS

By allowing you to inject data into templates, templating engines are essential tools for Node.js web development. This allows you to produce dynamic HTML pages. This method makes it possible to keep your HTML structures more manageable and your server-side code cleaner by separating concerns. There are a number of alternative strong templating engines that offer a variety of syntaxes and functionalities, even though EJS is a popular option for this purpose.

Nunjucks: A Powerful Templating Alternative

Nunjucks is a server-side templating engine that strongly resembles Twig (PHP) and was influenced by Jinja2 (Python). It has sophisticated features including asynchronous control, block inheritance, autoescaping, and macros.

To use Nunjucks with Express, you first need to install it via npm: npm i nunjucks.

You provide the location where your templates are kept and set up Express to use Nunjucks as your view engine after installation:

app.js (Nunjucks Configuration Example)

var express = require ('express');
var nunjucks  = require('nunjucks');
var app = express();
app.use(express.static('/public')); // Example of serving static files
// Apply nunjucks and add custom filter and function
var env = nunjucks.configure(['views/'], { // set folders with templates
    autoescape: true,
    express: app
});
// Example of a custom filter
env.addFilter('myFilter', function(obj, arg1, arg2) {
    console.log('myFilter', obj, arg1, arg2);
    return obj;
});
// Example of a custom global function
env.addGlobal('myFunc', function(obj, arg1) {
    console.log('myFunc', obj, arg1);
    return obj;
});
// Define routes that render Nunjucks templates
app.get('/', function(req, res){
    res.render('index.html', {title: 'Main page'});
});
app.get('/foo', function(req, res){
    res.locals.smthVar = 'This is Sparta!';
    res.render('foo.html', {title: 'Foo page'});
});
app.listen(3000, function() {
    console.log('Example app listening on port 3000...');
});

Like other templating languages, Nunjucks templates use a syntax that uses {%… %} for control flow and {{… }} for outputting variables. The directives {% extends… %} and {% block… %} are also used to allow template inheritance.

/views/index.html (Base Nunjucks Template)

<html>
<head>
    <title>Nunjucks example</title>
</head>
<body>
{% block content %}
{{title}}
{% endblock %}
</body>
</html>

/views/foo.html (Extended Nunjucks Template)

{% extends "index.html" %}
{# This is comment #}
{% block content %}
    <h1>{{title}}</h1>
    {# apply custom function and next build-in and custom filters #}
    {{ myFunc(smthVar) | lower | myFilter(5, 'abc') }}
{% endblock %}

By inheriting from index.html and using functions and filters, the output will dynamically render content based on the foo.html template when you visit http://localhost:3000/foo. Other advantages of using well-known frameworks like Nunjucks or Express include more employment prospects and a sizable community for help.

Advanced Static File Handling

In modern web applications, you often need to serve a combination of dynamic content and static files like HTML, CSS, JavaScript, images, and fonts. Express.js simplifies this process significantly.

Serving Static Files

The most common and organized way to serve static files in an Express application is by using the built-in express.static middleware. This middleware allows you to make an entire directory accessible via your web server without needing to define a custom route for each individual file.

A common practice is to create a folder named public (or static) at your project root to store all your static assets.

Project Folder Structure Example:

project root
├── server.js
├── package.json
└── public
    ├── index.html
    └── script.js
    └── css
        └── styles.css
    └── img
        └── me.png

To serve these files, you would use app.use() to register the express.static middleware, providing the path to your static directory:

server.js (Serving a Static Directory)

const express = require('express');
const app = express();
// Serve static files from the 'public' directory
app.use(express.static('public')); 
app.listen(3000, () => {
    console.log('Server is running on port 3000.');
});

With this setup, files inside the public directory can be accessed directly from the browser by their relative path. For example, public/index.html would be accessible at http://localhost:3000/index.html. Similarly, public/css/styles.css would be linked in your HTML as <link rel="stylesheet" href="/css/styles.css">.

If you want to make it available under a specific prefix, you can specify that as the first argument to app.use():

app.use('/static', express.static('public'));
// This would make files in 'public' accessible via '/static/filename.ext'

Serving Multiple Static Directories

Express allows you to define multiple static folders simultaneously. When serving it, Express examines these folders in the order they are defined. If files with the same name exist in different static directories, the one in the first matching folder will be served:

app.use(express.static('public'));
app.use(express.static('images'));
app.use(express.static('files'));

In this example, if a file named myimage.jpg exists in both public and images, the one in public will be served because public is defined first. This provides a flexible way to organize and serve assets from different locations within your application.

It’s important to note that res.sendFile() in Express streams a static file as a response but does not offer an opportunity to modify its content. If you need to include dynamic data within an HTML file, you should use a templating engine (like EJS or Nunjucks) instead of directly serving it as a static file.

For larger applications, while they don’t explicitly detail “asset pipelines” as a separate concept for serving, they do mention Grunt as a JavaScript Task Runner used for automation of repetitive tasks such as minification, compilation, and unit testing. These tasks are typically part of an asset pipeline, where raw assets are processed and optimized before being served as static files. This allows developers to maintain a consistent code style and ensure that their application’s assets are ready for production environments.

Using nodemon during development is also a common practice. It automatically restarts the server whenever code changes are detected, which is highly beneficial when working with static files and templates, saving you from manually restarting the server after every modification.

By combining robust templating engines with flexible static file serving, Node.js and Express provide powerful tools for building scalable and maintainable web applications.

Index