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.
Install
Section titled “Install”npm install @gaman/nunjucks nunjuckspnpm install @gaman/nunjucks nunjucksyarn install @gaman/nunjucks nunjucksbun install @gaman/nunjucks nunjucksHow to Use
Section titled “How to Use”Register Nunjucks
Section titled “Register Nunjucks”Add the Nunjucks middleware to your application:
import { nunjucks } from "@gaman/nunjucks";
defineBootstrap((app) => { app.mount( nunjucks({ viewPath: "src/views", // template folder extension: ".njk", // template file extension }) );});Creating Template
Section titled “Creating Template”Create the file src/views/index.njk
<!DOCTYPE html><html> <head> <title>{{ title }}</title> </head> <body> <h1>Hello, {{ name }}!</h1> </body></html>Render from Route
Section titled “Render from Route”In the route handler, use Res.render():
route.get("/", (ctx) => { return Res.render("index", { title: "My First Nunjucks Page", name: "GamanJS 🚀" });});Config Options
Section titled “Config Options”| 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. | | |
How: Adding Filters & Globals
Section titled “How: Adding Filters & Globals”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