Skip to content

Nunjucks

@gaman/nunjucks is the official middleware for integrating Nunjucks as a view engine in the GamanJS framework.

With this, you can render .njk template files (or other extensions) directly from the controller/handler using the built-in view system of GamanJS.

Terminal window
npm install @gaman/nunjucks nunjucks

Add the Nunjucks middleware to your application:

index.ts
import { nunjucks } from "@gaman/nunjucks";
defineBootstrap((app) => {
app.mount(
nunjucks({
viewPath: "src/views", // template folder
extension: ".njk", // template file extension
})
);
});

Create the file src/views/index.njk

<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>

In the route handler, use Res.render():

AppRoutes.ts
route.get("/", (ctx) => {
return Res.render("index", {
title: "My First Nunjucks Page",
name: "GamanJS 🚀"
});
});

| Name | Type | Default | Description |

|-------------|-------------------------------------------------------------|---------------|-----------|

| viewPath | string | "src/views" | Root directory where Nunjucks templates are located. |

| env | (env: Environment) => void | (env: Environment) => void[] | undefined | Callback to customize the nunjucks.Environment instance (e.g., adding filters, globals, extensions). Can be a single function or an array of functions. |

| extension | string | ".njk" | Default template extension. If the template name has no extension, it is automatically added. |

| (other options) | All options from Nunjucks ConfigureOptions except express. | | |

index.ts
import { nunjucks } from "@gaman/nunjucks";
defineBootstrap((app) => {
app.mount(
nunjucks({
env: (env) => {
env.addFilter("upper", (str: string) => str.toUpperCase());
env.addGlobal("appName", "GamanJS");
},
})
);
});

views/index.njk:

<h1>{{ appName | upper }}</h1>

Output:

<h1>GAMANJS</h1>

Please read the more detailed documentation about Nunjucks