You are currently offline, serving cached version
10 December 2024 : If you are using angular-expressions to parse expressions such as {user.name}, {#users.length > 10}, please upgrade asap to angular-expressions@1.4.3 for security reasons : View Github issue

Types of tags

Docxtemplater uses various types of tags to manage template data and control how the document is generated. This guide explains the different tags available, their syntax, and how to use them effectively in your templates.

Introduction

Tags in Docxtemplater are enclosed in curly braces : { and }. There are several types of tags, each serving a different purpose:

  • Placeholder Tags: {first_name}; These tags are used to insert data values (text) directly into the template.
  • Loop Tags: {#loop} and {/loop}; These tags define a loop for repeating sections based on array data.
  • Condition Tags: {#condition} and {/condition}; These tags are used to conditionally include or exclude content based on boolean values.
  • Raw XML Tags: {@input}; These tags are used to insert raw XML data into the document.
  • Image Tags: {%src_url}; Used with the image-module to insert images from URLs.
  • HTML Tags: {~~html}; Used with the html-module to insert HTML (tables, formatted text, ordered or unordered lists)
  • Subtemplate Tags: {:include doc}; Used with the subtemplate-module to insert the full content of an other docx file
  • Chart Tags: {$data}; Used with the chart-module to replace the data of a given docx/pptx native chart.

The syntax of Docxtemplater tags is inspired by the Mustache templating language.

Placeholder tags

Placeholder tags are used to insert data into the template. For example, with a tag like {name}, Docxtemplater will replace {name} with the corresponding value from the data object

Example

With this template (input.docx):

Hello {name} !

And given the following data (data.json):

{
    "name": "John"
}

docxtemplater will produce (output.docx):

Hello John !

Conditions

Condition tags control whether certain parts of the template are rendered based on the provided data.

Syntax

  • {#your_condition} starts a condition block
  • {/your_condition} ends it.

Example

Our goal here is to create a template that displays a Cat's name or Dog's name if and only if the data file says to do so.

With this template:

{#hasKitty}Cat’s name: {kitty}{/hasKitty}
{#hasDog}Dog’s name: {dog}{/hasDog}

and this data:

{
    "hasKitty": true,
    "kitty": "Minie"
    "hasDog": false,
    "dog": null
}

docxtemplater will render the following:

Cat’s name: Minie

For more details on conditions, see Sections

You can also create "else" blocks with Inverted Sections

Loops

A loop tag enables docxtemplater iterating over the data, for instance coping with arrays.

Syntax

Conditions and loops use the same syntax.

  • {#your_loop} starts a loop
  • {/your_loop} ends it.

Example

Our goal is to create a template that will be filled with data in an array of software licenses. For each license, the name and price need to be output.

With this template:

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

Given the following data:

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

docxtemplater will render :

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

Other example

To loop over an array containing primitive data (eg string):

Given the following template:

{#products}{.} {/products}

and following data:

{
    "products": ["Windows", "Mac OSX", "Ubuntu"]
}

Will result in:

Windows Mac OSX Ubuntu

Sections

Sections allow you to include blocks of content that are conditionally rendered based on the provided data.

Syntax

  • {#your_section} starts a section
  • {/your_section} ends it.

Behavior

Type of the valuethe section is shownscope
falsy or empty arrayneverNA
non empty arrayfor each element of arrayelement of array
objectoncethe object
other truthy valueonceunchanged

This table shows for each type of value, whether or not the section content is rendered and what is the scope of that section.

Examples

Non empty array

Our goal here is to output a list of fruits.

Given the following template,

{#fruits}
{.}
{/fruits}

and given the following data:

{
    "fruits": ["banana", "apple"]
}

docxtemplater will output:

banana
apple

Empty array

Given the following template

{#fruits}
{.}
{/fruits}

Given the following data:

{
    "fruits": []
}

docxtemplater will output an empty document:


Object

In this scenario, the people data is a single object representing one person with details like name, age, and occupation.

Given the following template

{#people}
{name}
{age}
{occupation}
{/people}

Given the following data:

{
    "people": {
        "name": "Alice",
        "age": 30,
        "occupation": "Engineer"
    }
}

docxtemplater will output document:

Alice
30
Engineer

Explanation: {#people} opens the section where people is the context. Inside the section, {name} refers to people.name, {age} refers to people.age, and {occupation} refers to people.occupation. Since people is an object, docxtemplater accesses its properties directly within the section.

Truthy value

If the value is of type boolean, the section is shown once if the value is true, and the scope of the section is unchanged.

If we have the following template,

{#hasProduct}
{price} €
{/hasProduct}

and the following data,

{
    "hasProduct": true,
    "price": 10
}

docxtemplater will output:

10 €

Since hasProduct is a boolean, the section is shown once if hasProduct is true. Since the scope is unchanged, the subsection {price} € rendered as [10 €]

This is precisely the behavior of a condition tag. In fact, a condition
tag is a section tag.

Creating multiple table rows

To create tables with varying numbers of rows, use loop tags within table cells.

You need to place the start of a loop in the first column cell, and the end of the loop in the last cell of the same row.

Example

Our goal here is to create a table that contains name, age and phone number for each of our users.

If we have the following template:

NameAgePhone Number
{#users}{name}{age}{phone}{/}

Given the following data:

{
    "users": [
        {
            "name": "John",
            "age": 22,
            "phone": "+33777777777"
        },
        {
            "name": "Mary",
            "age": 25,
            "phone": "+33666666666"
        }
    ]
}

Will render the following :

NameAgePhone Number
John22+33777777777
Mary25+33666666666

docxtemplater automatically interprets the closing tag {/} as
{/users}.

Inverted Sections

Inverted sections are the opposite of regular sections; they render content if the key doesn't exist, is false, or is an empty list.

Syntax

  • {^your_inverted_section} begins a "your_inverted_section" inverted section
  • {/your_inverted_section} ends it.

Example

Template:

{#repo}
Repo name : {name}
{/repo}
{^repo}
No repos :(
{/repo}

Data:

{
    "repo": []
}

Output:

No repos :(

Explanation:

Because repo is an empty array, the inverted section using repo is rendered but not the section.

Raw XML

If you need to render a complex table or an equation, it's possible to insert raw (unescaped) XML.

Syntax

-{@input} inserts raw XML data

Example

We want to add to the template a Word Paragraph written in rawXml.

Given the following template:

{@rawXml}

with this data,

doc.render({
    rawXml: `
    <w:p>
        <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 paragraph
            </w:t>
        </w:r>
    </w:p>
    `,
});

docxtemplater will render:

My custom XML paragraph

With the rawXML syntax the whole current paragraph (<w:p> tag) is
replaced by the XML passed in the value.

HTML

For inserting HTML directly into your document, use the docxtemplater html module. Refer to its specific documentation for more details.

Newlines and the paragraphLoop option

In docxtemplater, newlines (paragraph breaks) are handled in a straightforward manner, but the interaction between docxtemplater tags and newlines can sometimes lead to unexpected outputs.

To manage newlines effectively, you can use the paragraphLoop option to remove unwanted line breaks.

Example

If your docxtemplater template includes paragraph breaks within a section, those newlines will also appear in the output by default.

Given the template,

{#repo}
{name}
{/repo}

and the data,

{
    "repo": [{ "name": "John" }, { "name": "Jane" }]
}

the output with the default settings will be :

NL
John
NL
NL
Jane
NL

(where NL represents an emptyline)

docxtemplater iterates over each item in the repo array. For
each item, it outputs {name} and includes the newlines present in the
template.

Solution

Enable the paragraphLoop option to avoid these paragraph breaks:

const doc = new Docxtemplater(zip, { paragraphLoop: true });
// Now, all sections in the form of :
// {#section}
// something
// {/section}
// will keep just the inner paragraphs, and drop the newlines of the outer section
doc.render(/* data */);

Alternatively (less recommended), manually remove the newlines:

For our example , that would be:

{#repo} {name}
{/repo}

This would render:

John
Jane

Lambdas

A Lambda refers to a function that is defined without being bound to an identifier. This is a common feature of JavaScript. You can use lambdas in docxtemplater to perform custom processing.

Example

Given the following Javascript:

const doc = new Docxtemplater(zip);
doc.render({
    userGreeting: (scope) =>
        "How is it going, " + scope.user + " ?",
    users: [
        {
            name: "John",
        },
        {
            name: "Mary",
        },
    ],
});

with the following template :

{#users}
{userGreeting}
{/}

Docxtemplater will render :

How is it going, John ?
How is it going, Mary ?

Detailed explanation

Docxtemplater will call the function userGreeting twice (one for the user "John", and for the user "Mary").

The {#users} section loops over each user. Inside the section, the scope is set to the current user being processed. As userGreeting is taking the scope as first argument and the scopeManager as a second argument implicitly, userGreeting is fed with the current user.

Technical note: if you're not familiar with the concept of scope, the scope determines which data is available at different points in the template and drives the rendering of placeholders and functions. This is an important notion to know in JavaScript and other programming languages.

Set Delimiter tag

docxtemplater templates use default delimiters { and } to enclose placeholders and logic.

Problem: If your template also needs to contain "{" or "}" characters outside of tags, you might need to change the delimiter tag from inside your template.

Solution: By customizing delimiters, you avoid conflicts and ensure that docxtemplater correctly interprets your template placeholders.

In order to customize the delimiters you can use our 'Set Delimiter tags'. A 'Set Delimiter tags' starts with an equal sign and changes the tag delimiters from { and } to custom strings.

Example

Given the following template:

{first_name}
{=<% %>=}
<%first_name%>
<%={ }=%>
{last_name}

The following data:

{
    "first_name": "John",
    "last_name": "Doe"
}

Docxtemplater will output:

John

John

Doe

Technical note: custom delimiters may not contain whitespace or the equals sign.

Other solutions and options available

Changing the delimiters globally

You can change the delimiters globally by using docxtemplater options object.

Removing the "change delimiter" tag behavior

If you want to use a tag like {=foo}, you can remove the default "change delimiter" tag behavior by using the following code:

const doc = new Docxtemplater(zip, {
    paragraphLoop: true,
    linebreaks: true,
    syntax: {
        changeDelimiterPrefix: null,
    },
});
doc.render(data);
Changing the char used to change the delimiters

To use a different character, such as $, to change delimiters, use the following code:

const doc = new Docxtemplater(zip, {
    paragraphLoop: true,
    linebreaks: true,
    syntax: {
        changeDelimiterPrefix: "$",
    },
});
doc.render(data);

That way,

Using the following template,

{$<% %>$}
<%first_name%>

with the following data:

{
    "first_name": "John"
}

docxtemplater will render:

John

Dash syntax

In docxtemplater, the Dash syntax provides a way to control how sections are rendered, especially when looping over elements in a DOCX template. It helps specify where and how the loop should expand, making template rendering more flexible.

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

  • there is a table cell tag (<w:tc> or <a:tc>) , that means that your loop is inside a table, and it will expand the loop over the table row (<w:tr> or <a:tr>).
  • in other cases it won't expand the loop

With Dash syntax, you can explicitly specify the tag to loop over. For instance, if you want to loop over paragraphs (w:p), creating a new paragraph for each item, you can write:

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

Example

Given the following data,

{
    "users": [{ "name": "John" }, { "name": "Mary" }]
}

using the following template,

{-w:p users}{name}{/}

docxtemplater will render:

John
Mary

The example above has created two paragraphs (one for each user). If you
were using a normal loop like {#users}{name}{/}, it would output each user
name on the same paragraph.

Talk with sales Contact us