Syntax

The syntax is highly inspired by Mustache. The template is created in Microsoft Word or any equivalent that saves to docx.

Synopsis

A typical docxtemplater template:

Hello {name} !

Given the following data:

{
    name:'Edgar'
}

Will produce:

Hello Edgar !

Tag types

Like Mustache, it has the loopopening {#} and loopclosing {/} brackets

Loop syntax

The following template:

{#products}
    {name}, {price} €
{/products}

Given the following data:

{
    "products":
        [
         {name:"Windows",price:100},
         {name:"Mac OSX",price:200},
         {name:"Ubuntu",price:0}
        ]
}

will result in :

Windows, 100 €
Mac OSX, 200 €
Ubuntu, 0€

The loop behaves in the following way:

  • If the value is an array, it will loop over all the elements of that array.
  • If the value is a boolean, it will loop once if the value is true, keeping the same scope, and not loop at all if the value is false

Conditionals

Because the loops work with boolean values, you can also use them for conditions. This allows optional fields in your data. For example, this template:

{#people}
First name: {first_name}
Last name: {last_name}
{#haskitty}Cat’s name: {kitty}{/haskitty}{/people}

and this data:

yield the following:

First name: Jane
Last name: Doe

First name: John
Last name: Roe
Cat’s name: Chairman Meow

Dash syntax

It is quite difficult to know on which element you are going to loop. By default, when using the for loop, docxtemplater will find that by himself:

If between the two tags {#tag}______{/tag}

  • they is the Xml Tag <w:tc> -> you are in a table, and it will loop over <w:tr>
  • else -> it will loop over <w:t>, which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on:

{-w:p loop} {inner} {/loop}

In this case this will loop over the first parent <w:p> tag

Raw Xml syntax

Sometimes, you would like to insert your custom XML (a complex table, a formula, ...)

With the RawXml syntax the variable is interpreted as XML and replaced in the formula

{@rawXml}

with this data:

{rawXml:'<w:p><w:pPr><w:rPr><w:color w:val="FF0000"/></w:rPr></w:pPr><w:r><w:rPr><w:color w:val="FF0000"/></w:rPr><w:t>My custom</w:t></w:r><w:r><w:rPr><w:color w:val="00FF00"/></w:rPr><w:t>XML</w:t></w:r></w:p>'}

This will loop over the first parent <w:p> tag

Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash. That is {^person} begins a “person” inverted section while {/person} ends it.

While sections can be used to render text one or more times based on the value of the key, inverted sections may render text once based on the inverse value of the key. That is, they will be rendered if the key doesn’t exist, is false, or is an empty list.

Template:

{#repo}
  <b>{name}</b>
{/repo}
{^repo}
  No repos :(
{/repo}

Data:

{
  "repo": []
}

Output:

No repos :(