@fnet/njk

0.1.3 • Public • Published

@fnet/njk

This project offers a lightweight templating engine based on Nunjucks that enables efficient and structured rendering of HTML templates. Designed for users who need a simple method for template rendering, it provides flexible options for template storage, caching, and customized settings. By utilizing this tool, you can facilitate the generation of dynamic content in web applications or any environment that requires HTML templates.

How It Works

The project operates by allowing you to define templates that can be populated with dynamic data. Templates can be stored either in files within a specified directory or in-memory. The Engine class initializes the template system, configuring Nunjucks with options such as caching and customized block stripping. Users interact with templates via a dynamic path-based approach, enabling easy access to various template files.

Key Features

  • Dynamic Method Chaining: Access nested templates using a proxy-based path method.
  • Caching: Optional caching for efficient template reuse, reducing the need for repeated file reads.
  • Flexible Directory and Extensions: Designate where templates are stored and specify allowable file extensions.
  • Context Support: Pass additional configurations for template handling and rendering.
  • Nunjucks Integration: Leverages Nunjucks for rendering templates, supporting features like autoescape and block trimming.

Conclusion

@fnet/njk provides a straightforward way to manage and render templates in applications that require consistent HTML or text content generation. Its simplicity and integration with Nunjucks make it a practical choice for developers seeking a basic yet effective templating solution.

Developer Guide for @fnet/njk

Overview

The @fnet/njk library provides a streamlined interface for rendering Nunjucks templates. By offering a set of features through its public API, developers can easily manage templates from either a specified directory or in-memory, with optional caching capabilities. This library is particularly useful for projects that need dynamic content rendering using nested template paths efficiently.

Installation

To install @fnet/njk, use npm or yarn:

npm install @fnet/njk

or with yarn:

yarn add @fnet/njk

Usage

Configuring and Using the Engine

  • Create an Engine: Use the primary export index to create an instance of the Engine.
import createEngine from '@fnet/njk';

const args = {
  templatesDir: './templates', // Directory for templates
  useCache: true, // Enable template caching
  extensions: ['njk'], // File extensions for templates
};

const context = {}; // Additional context if needed

async function main() {
  const engine = await createEngine(args, context);
  
  // Access the template instance
  const template = engine.template;

  // Render a template
  const result = await template.example.run({ name: 'John Doe' });
  console.log(result);
}

main();

Working with Templates

  • Render a Template: Use the run method to render a template by specifying the path and parameters.
const greetingMessage = await engine.tmpl.greetings.run({ person: 'Alice' });
console.log(greetingMessage);
  • Clear Cache: Clear the cache if caching is enabled and you need to refresh the templates.
engine.template.clearCache();

Examples

Render a Simple Template

Place your Nunjucks templates in a directory, such as ./templates/greetings.njk, with content like:

Hello, {{ person }}!

Then, use the @fnet/njk library to render it:

const args = {
  templatesDir: './templates',
};

async function renderGreeting() {
  const engine = await createEngine(args);
  const message = await engine.template.greetings.run({ person: 'Bob' });
  console.log(message); // Outputs: Hello, Bob!
}

renderGreeting();

Nested Template Paths

Templates can be nested in directories, allowing for structured project layouts:

// Directory structure:
// ./templates/messages/email.njk

const emailMessage = await engine.tmpl.messages.email.run({ recipient: 'Sarah' });
console.log(emailMessage);

Acknowledgement

This guide and the @fnet/njk library are inspired by and use the core capabilities of the Nunjucks templating engine. Many thanks to all contributors who make such projects possible.

Input Schema

$schema: https://json-schema.org/draft/2020-12/schema
title: EngineArgumentSchema
type: object
properties:
  templatesDir:
    type: string
    description: Directory where templates are stored
    default: ./templates
  useCache:
    type: boolean
    description: Whether to enable caching for templates
    default: false
  extensions:
    type: array
    description: Allowed file extensions for templates
    items:
      type: string
    default:
      - njk
  trimBlocks:
    type: boolean
    description: Remove the first newline after a block, default is true if not provided
    default: true
  lstripBlocks:
    type: boolean
    description: Strip leading whitespace from the start of a block, default is true
      if not provided
    default: true
  throwOnUndefined:
    type: boolean
    description: Throw errors when outputting a null/undefined value, default is
      false if not provided
    default: false
  autoescape:
    type: boolean
    description: Escape dangerous characters automatically, default is true if not provided
    default: true
required: []
additionalProperties: false
$defs:
  context:
    type: object
    description: Context for additional configurations

Readme

Keywords

none

Package Sidebar

Install

npm i @fnet/njk

Weekly Downloads

174

Version

0.1.3

License

MIT

Unpacked Size

32.2 kB

Total Files

6

Last publish

Collaborators

  • serdark
  • serdar986
  • gboyraz