Skip to content

Latest commit

 

History

History
141 lines (96 loc) · 5.33 KB

File metadata and controls

141 lines (96 loc) · 5.33 KB

API Reference

const NHP = require("nhp");

new NHP(constants?, options?)

Creates an NHP renderer. constants are copied into every render context. options configures output handling.

const nhp = new NHP(
    { siteName: "Example" },
    { tidyOutput: true }
);

Options

Option Default Meaning
tidyOutput true Parse and normalize rendered HTML output.
tidyAttribs ['false', 'null', 'undefined'] Attribute values omitted during output tidying.
tidyComments 'not-if' Removes ordinary comments while retaining conditional comments.

Set tidyOutput: false when the destination should receive the raw output written by the template.

Rendering

nhp.render(filename, locals, callback)

Compiles, caches, and renders a template. The callback receives (error, html).

nhp.render("views/page.nhp", { title: "Docs" }, (error, html) => {
    if (error)
        return handleError(error);
    response.send(html);
});

nhp.renderToStream(filename, locals, stream, callback)

Renders to a writable stream and closes it when rendering completes.

nhp.renderToStream("views/page.nhp", locals, response, (error) => {
    if (error)
        response.destroy(error);
});

nhp.template(filename, mutable?)

Returns a cached Template. NHP appends .nhp when the filename has no extension. Templates are mutable by default and watch their source file for changes. Pass false for one-shot or build-time rendering:

const template = nhp.template("views/page", false);
template.render({ title: "Static" }, callback);

nhp.genSource(filename, callback?)

Compiles a template and returns its internal generated JavaScript instructions with (error, source) or as a Promise<string>.

nhp.genCompiledSource(filename, callback?)

Compiles a template and returns its executable compiled function JavaScript string with (error, source) or as a Promise<string>.

nhp.genModule(filename, callback?) / nhp.generateModule(filename, callback?)

Compiles a template and returns a standalone JavaScript Node.js module string with (error, moduleSource) or as a Promise<string>. The resulting code can be written to a .js file and imported with require().

Generated modules are self-contained: <?include "literal/path"?> directives are inlined into the module at compile time, and the module's own render(locals) / renderToStream(locals, stream) build their render context directly from locals without calling into nhp or any of its dependencies. require("nhp") only happens lazily, inside the specific pieces that inherently need a real NHP instance:

Feature Why it needs nhp
createTemplate(nhp?, options?) Builds a full Template (file watching, caching, tidy output) instead of the lightweight renderer.
Dynamic <?include expression?> (a non-literal path) Only resolvable at runtime through nhp.template(); static includes are inlined and never reach this path.
{{#resolverName}} moustaches Resolvers are registered per-instance with installResolver(), so one is required to look them up.

Passing { nhp: existingInstance } as the options argument to the generated module's render/renderToStream reuses that instance's constants and resolvers instead of lazily creating a bare one.

NHP.Template.fromCompiled(filename, compiledScript, variables?, nhp?)

Creates a Template instance from a precompiled template script without requiring the original .nhp file on disk.

template.generateModule() / template.genModule()

Generates a standalone Node.js module string from an existing Template instance. See Command line for the exact shape and behavior of the generated module.

nhp.__express()

Returns a function compatible with Express's view-engine signature.

Constants

Method Description
setConstant(name, value) Adds a constant. Throws when the name already exists.
constant(name) Gets a constant value.
hasConstant(name) Tests whether a constant is set.
deleteConstant(name) Deletes a constant and returns whether it was deleted.
assignConstants(values) Merges values into the constant context.

Extensions

Resolvers

installResolver(name, resolver) registers an asynchronous provider for {{#name}}. The resolver receives an error-first callback:

nhp.installResolver("buildId", (callback) => {
    callback(undefined, process.env.BUILD_ID);
});

Processors

installProcessor(name, processor) registers a processing-instruction factory. A processor receives the source text inside <?name ...?> and returns an instruction. The built-in instruction constructors are exposed as NHP.Instructions for advanced extensions.

nhp.installProcessor("notice", (text) => {
    return new NHP.Instructions.Custom(() => {
        return "__out.write(" + JSON.stringify(text) + ");";
    });
});

Use processingInstruction(name, data) to create an instruction through the currently registered processor map. It throws for an unknown name.

Lifecycle

destroy() closes file watchers for every cached template. Call it when a short-lived process has finished rendering or when an application shuts down:

process.on("SIGTERM", () => {
    nhp.destroy();
    process.exit(0);
});