Skip to content

Latest commit

 

History

History
89 lines (64 loc) · 1.88 KB

File metadata and controls

89 lines (64 loc) · 1.88 KB

Getting Started

Install

Install NHP as a project dependency:

npm install nhp

NHP requires Node.js 20.19.0 or newer.

Create a template

Create views/page.nhp:

<!doctype html>
<html>
  <body>
    <h1>{{title}}</h1>
    <p>{{message}}</p>
  </body>
</html>

{{expression}} evaluates JavaScript against the render environment. NHP awaits the result and HTML-escapes normal moustache output.

Render HTML

Without a callback, rendering returns a promise:

const NHP = require("nhp");

const nhp = new NHP();
const html = await nhp.render("views/page.nhp", {
  title: Promise.resolve("Welcome"),
  message: "Rendered on the server"
});
nhp.destroy();

Error-first callbacks are also supported:

const NHP = require("nhp");

const nhp = new NHP();
nhp.render("views/page.nhp", {
    title: "Welcome",
    message: "Rendered on the server"
}, (error, html) => {
    nhp.destroy();
    if (error)
        throw error;
    console.log(html);
});

Templates are compiled asynchronously the first time they are used. render() waits for compilation and for promises returned by template expressions before completing.

Express view engine

Use the bound __express() function as an Express engine:

const express = require("express");
const NHP = require("nhp");

const app = express();
const nhp = new NHP();

app.engine("nhp", nhp.__express());
app.set("views", "./views");
app.set("view engine", "nhp");

app.get("/", (request, response) => {
    response.render("page", { title: "Home", message: "Hello" });
});

Call nhp.destroy() during application shutdown to close file watchers for cached templates.

Next steps