0

https://docxtemplater.com/docs/installation/#browser-js-files

Hi, I am working on the latest release (also tried with 3.31.2 and 3.9.9 but when I define the following variables:

    // Render the document (Replace {first_name} by John, {last_name} by Doe, ...)
                doc.render({
                    test : "yes",
                });

and I have the following Word template:

{#test == "yes"}
They are many users.
{/test == "yes"}

it does not work, it does not render anything. Already tried to:

  • replace the test string with numbers, not working;
  • use any type of double and single quote in Word, not working.

Only the boolean condition works.

Is this a bug? Anyone can help please?

Thanks, Mauro

Mauro
  • 102
  • 14

1 Answers1

0

Docxtemplater has support for conditions, and it has to be enabled (it is not by default).

The simplest setup would be to first install angular-expressions and lodash :

npm install --save angular-expressions lodash

Then use following code sample :

var expressions = require("angular-expressions");
var assign = require("lodash/assign");
// define your filter functions here, for example
// to be able to write {clientname | lower}

function angularParser(tag) {
    tag = tag
        .replace(/^\.$/, "this")
        .replace(/(’|‘)/g, "'")
        .replace(/(“|”)/g, '"');
    const expr = expressions.compile(tag);
    return {
        get: function (scope, context) {
            let obj = {};
            const scopeList = context.scopeList;
            const num = context.num;
            for (let i = 0, len = num + 1; i < len; i++) {
                obj = assign(obj, scopeList[i]);
            }
            return expr(scope, obj);
        },
    };
}
new Docxtemplater(zip, { parser: angularParser });

See the following doc :

https://docxtemplater.com/docs/angular-parse/

Note that is also possible to add some "filters", like this :

expressions.filters.lower = function (input) {
    // This condition should be used to make sure that if your input is
    // undefined, your output will be undefined as well and will not
    // throw an error
    if (!input) return input;
    return input.toLowerCase();
};

Which will allow you to write {client.name | lower} in your template to make a string lowercase.

edi9999
  • 19,701
  • 13
  • 88
  • 127