livecode-static/docs/languages/nunjucks.html.md
2025-06-11 22:23:49 +08:00

2.7 KiB

Nunjucks

Nunjucks is a rich and powerful templating language for JavaScript.

Usage

There are 2 modes for rendering:

Pre-rendered (Default)

The values of the expressions are evaluated and added to the template during compilation of the result page.

The values of all expressions should be supplied in advance using custom settings to the property template.data which accepts an object of key-value pairs.

Example: This provides the value of the expression name

{
  "template": {
    "data": {
      "name": "LiveCodes"
    }
  }
}

Full example below

Dynamic

To use this mode, the property template.prerender in custom settings should be set to false.

Example:

{
  "template": {
    "prerender": false
  }
}

In this mode, in addition to values supplied in custom settings (see above), expressions can have values that are evaluated during the result page runtime.

This can be achieved in JavaScript (or any language that compiles to it) by assigning window.livecodes.templateData to an object with the data.

Please note that template rendering occurs on page load, so the assignment must occur before that.

Example:

window.livecodes.templateData = { name: 'LiveCodes' };

Full example below

Language Info

Name

nunjucks

Extension

.njk, .nunjucks

Editor

markup

Compiler

The official Nunjucks compiler.

Version

nunjucks: v3.2.3

Code Formatting

Using Prettier.

Example Usage

import LiveCodes from '../../src/components/LiveCodes.tsx';

Pre-rendered

export const config = { markup: { language: 'nunjucks', content: 'Hello {{name}}!' }, customSettings: { template: { data: { name: 'LiveCodes' } } }, };

export const params = { compiled: 'open' };

Dynamic

export const config2 = { markup: { language: 'nunjucks', content: 'Hello {{name}}!' }, script: { language: 'javascript', content: 'window.livecodes.templateData = { name: "LiveCodes" };', }, customSettings: { template: { prerender: false } }, activeEditor: 'script', };