template

Builds a form from a fenced ```template block written in YAML. Readers fill in the form and get a rendered text file, such as a Kubernetes manifest, a compose file or a script, with Copy, Download and Copy link buttons. Rendering runs in the browser with Nunjucks, so it works on a static site.

First-party Netdocs plugin, no MkDocs equivalent. Enable it in plugins:

appsettings.json
{ "name": "template" }

Example

A Deployment form with inputs, an environment variable group, file tabs and the rendered YAML

The form for the example below. The output updates as the inputs change.
```template
title: Deployment
id: deploy
inputs:
  - name: name
    type: string
    required: true
    maxlen: 63
    regex: "[a-z0-9]([-a-z0-9]*[a-z0-9])?"
    help: Lowercase letters, digits and dashes.
    default: web
  - name: namespace
    type: string
    default: default
  - name: image
    type: string
    default: nginx:1.27
  - name: replicas
    type: int
    min: 1
    max: 20
    default: 2
  - name: expose
    label: Create a Service
    type: bool
    default: true
  - name: port
    label: Service port
    type: int
    min: 1
    max: 65535
    default: 80
    show_if: expose
  - name: env
    label: Environment variables
    type: group
    add_label: + Add variable
    fields:
      - name: key
        required: true
      - name: value
    default:
      - key: LOG_LEVEL
        value: info
outputs:
  - filename: "{{ name }}-deployment.yaml"
    language: yaml
    template: |
      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: {{ name }}
        namespace: {{ namespace }}
      spec:
        replicas: {{ replicas }}
        selector:
          matchLabels:
            app: {{ name }}
        template:
          metadata:
            labels:
              app: {{ name }}
          spec:
            containers:
              - name: {{ name }}
                image: {{ image | quote }}
      {% if env | length %}
                env:
      {% for e in env %}
                  - name: {{ e.key }}
                    value: {{ e.value | quote }}
      {% endfor %}
      {% endif %}
  - filename: "{{ name }}-service.yaml"
    language: yaml
    template: |
      {% if expose %}
      apiVersion: v1
      kind: Service
      metadata:
        name: {{ name }}
        namespace: {{ namespace }}
      spec:
        selector:
          app: {{ name }}
        ports:
          - port: {{ port }}
      {% else %}
      # No Service
      {% endif %}
```

Renders as:

Deployment
Lowercase letters, digits and dashes.
Environment variables
Loading…

Block fields

Field Type Description
title string Shown above the form. Also the default file name.
description string One line under the title.
class string Extra CSS classes on the form, separated by spaces. See Styling.
id string Prefix for this form's values in share links (?deploy.name=api). Needed when a page has more than one form with the same input names.
definition_file string Read the definition from a YAML file. See Shared definitions.
inputs list The form fields. See Inputs.
vars map Computed values. See Computed values.
presets list Named sets of values. See Presets.
template string The Nunjucks template for a single output file.
template_file string Read the template from a file instead. Relative to the page, or to the docs folder when it starts with /. Must be inside the project.
output map filename, language and validate for a single output file.
outputs list Two or more output files, shown as tabs. Each has filename, language, validate and template or template_file.
zip_name string File name for Download all, shown with two or more outputs. Can use template values. Defaults to the title.

filename can use template values ("{{ name }}.yaml"). Without it, the name comes from the title and language (deployment.yaml). language sets highlighting and the file extension. For yaml and json output, the rendered text is parsed and a warning shows when it is not valid. Set validate: false to turn that off.

Inputs

Each entry under inputs:

Field Applies to Description
name all Variable name in the template. Letters, digits and _, starting with a letter.
label all Field label. Defaults to name.
type all string, text, password, int, number, bool, select, list or group. Defaults to string, or select when options is set.
widget some textarea for string, range (slider) for int and number, radio for select.
default all Starting value. For list and group, a list of starting rows.
required all The field must have a value. For list and group, at least one row.
show_if all Show the field only when this condition is true. See Conditional fields.
minlen / maxlen string, text, password Length limits.
regex string, text, password The whole value must match. JavaScript regex syntax.
min / max / step int, number Number limits. int steps by 1, number takes any decimal.
options select Strings, or { value, label } maps.
placeholder string, text, password Hint text inside the empty field.
generate password Adds a Generate button that fills in a random value of this length (letters and digits). true means 24.
help all Hint text under the field.

A form with an invalid name and an empty required row field, each with an error under it

Invalid fields show an error and dim the output until they are fixed.

The template gets typed values: numbers for int and number (null when empty), true or false for bool, strings for the rest.

A password field is masked, with a Show button. Its value is never put in share links.

Lists and groups

list is a list of single values with Add and remove buttons. The template gets an array of strings. item_type sets the value type (string, int, number, select, text) and item_label its label. The input's own regex, maxlen, options and so on apply to each value.

group is a list of rows with several fields each, such as environment variables or ports. The template gets an array of objects keyed by the field names. fields lists the row fields, which take the same settings as inputs (any type except list and group).

Field Description
fields Row fields (group only).
min_items / max_items Row count limits. required: true sets min_items to 1.
add_label Text of the add button. Default + Add.
inputs:
  - name: hosts
    type: list
    regex: "[a-z0-9.-]+"
    default: [example.com]
  - name: ports
    type: group
    fields:
      - name: port
        type: int
        min: 1
        max: 65535
        required: true
      - name: protocol
        options: [TCP, UDP]
    default:
      - port: 80
        protocol: TCP

Conditional fields

show_if is a Nunjucks condition, written as in {% if %}, over the other inputs and vars. The field shows only while it is true. A hidden field is not validated, and the template gets null for it (an empty list for list and group).

inputs:
  - name: expose
    type: bool
  - name: port
    type: int
    show_if: expose
  - name: kind
    options: [Deployment, StatefulSet]
  - name: storage
    show_if: kind == "StatefulSet"

The same form before and after checking Create a Service, with Service port appearing

port has show_if: expose. It shows when Create a Service is checked.

A field in a group row can also use the other fields of its row, by name or as row.<name>.

Computed values

vars maps names to templates that are rendered from the inputs before the output. Each is a string, trimmed, and can be used in the output templates, file names and show_if like an input. Later entries can use earlier ones. Names must not clash with input names.

vars:
  fullname: "{{ name }}-{{ env }}"
  image_ref: "{{ registry }}/{{ fullname }}:{{ tag }}"

Presets

presets adds a Preset list above the form. Picking one sets the inputs it lists. Other inputs keep their values. Values for list and group inputs are lists of rows.

presets:
  - name: Small
    values: { replicas: 1, cpu: 250m }
  - name: Production
    values:
      replicas: 3
      cpu: "1"
      env:
        - { key: LOG_LEVEL, value: warn }

A form with the Production preset picked, three file tabs and the Download all button

The Production preset set the environment, replicas, Service and port. With three outputs, the files show as tabs and Download all saves a zip.

Shared definitions

definition_file reads the block's keys from a YAML file, so several pages can use the same generator. The path is relative to the page, or to the docs folder when it starts with /, and must be inside the project. Keys in the block override the file's. template_file paths in the file are relative to the file. A block that sets template, template_file or outputs replaces the file's templates.

```template
definition_file: /generators/deployment.yaml
title: API deployment
```

Templates

Templates use Nunjucks, which follows Jinja2 syntax: {{ value }}, {% if %}, {% for %}, filters with |. Autoescaping is off, since the output is plain text. trimBlocks and lstripBlocks are on, so a line that holds only a {% %} tag leaves no blank line or indentation behind.

Filters added by the plugin, next to the Nunjucks built-ins (default, lower, upper, replace, indent, join, length and others):

Filter Output
quote A double-quoted string, valid in YAML and JSON: {{ image \| quote }} → "nginx:1.27".
yaml The value as YAML. Combine with indent for nested blocks: {{ labels \| yaml \| indent(4) }}.
json(indent) The value as JSON.
b64 Base64 of the UTF-8 text, for Kubernetes Secrets.

Functions:

Function Output
uuid() A random UUID (version 4).
random(n) n random letters and digits (default 16, at most 256).

Each uuid() and random() call keeps its value while the form is edited. A New random values button shows when the template uses them, and makes new ones. Values come from the browser's crypto.getRandomValues.

A Secret file with a generated database password, a random session key and a UUID, all base64 encoded

A generated password shown with Hide, and random(32) and uuid() in a Secret.

A template error shows under the output instead of the file.

Copy link copies the page URL with every value that differs from its default as a query parameter, plus an anchor to the form. Opening the link fills the form with those values. list and group values are JSON. With id set, parameters are named <id>.<name>. password values are left out.

Download all

With two or more outputs, Download all saves every file in one zip. The zip is built in the browser.

Styling

The theme styles the form in netdocs.css, with the theme's color variables, so it follows the light and dark palettes. To change it, add a stylesheet with extraCss and override the classes below. The class names are stable. Set class on a block to style one form differently:

appsettings.json
{ "Netdocs": { "extraCss": ["assets/template.css"] } }
docs/assets/template.css
/* Every form: taller output */
.md-typeset .nd-template__pre > code { max-height: 48rem; }

/* Forms with `class: wide`: one input per row */
.nd-template.wide .nd-template__inputs { grid-template-columns: 1fr; }

Classes

Class Element
nd-template The <form>. Also carries the block's class.
nd-template--invalid Added to the form while a field is invalid.
nd-template--error A box shown instead of the form when the block definition has errors.
nd-template__title / __description Title and description.
nd-template__presets The preset label and <select>.
nd-template__inputs Grid that holds the fields and groups.
nd-template__field One field: label, control, help and error.
nd-template__field--check A bool field.
nd-template__field--invalid A field whose value is invalid.
nd-template__label Label of a radio group.
nd-template__radios The radio buttons of a select with widget: radio.
nd-template__range Value shown next to a slider.
nd-template__secret Password input with its Show and Generate buttons.
nd-template__small The Show and Generate buttons.
nd-template__required The * after a required field's label.
nd-template__help Help text under a field.
nd-template__error Error text under a field or group.
nd-template__group <fieldset> of a list or group input.
nd-template__rows / __row The rows of a group, and one row.
nd-template__remove / __add Row remove button, and the add button.
nd-template__output Everything below the inputs.
nd-template__tabs / __tab File tabs, with aria-selected="true" on the open one.
nd-template__bar Row with the file name and buttons.
nd-template__filename File name (hidden when tabs show).
nd-template__actions / __btn The output buttons. They also have md-button.
nd-template__status Template errors and output warnings. --error and --warning set the color.
nd-template__pre / __code The rendered output. __pre--stale while the form is invalid.

Hidden fields (show_if) have the hidden attribute. Buttons and fields also have data-tpl-* attributes, which the page script uses: data-tpl-var="<name>" on each input control, data-tpl-group="<name>" on each group and data-tpl-show on fields with a condition. They can be used as selectors, for example [data-tpl-var="image"] { font-family: var(--md-code-font-family); }.

How it works

The plugin runs as a Markdown preprocessor (order 15) and replaces each template fence with a raw-HTML form. Fields use the same markup as the calculator. The templates go into the page as base64 JSON, so later preprocessors such as macros, which also expands {{ }}, leave them alone.

The page script is registered once for the whole site. On a page with a form it loads Nunjucks 3.2.4 and js-yaml 4.1.0 from jsDelivr. With optimize.offline, both are downloaded into the site like other CDN assets.

CMS

In the visual editor, a template block opens a form for its inputs, computed values, presets and output files, and Template generator in the insert menu adds a working example.