Search code examples
docxtemplater

Docxtemplater variable data keys


I need to generate a docx from a data set in which there are variable tag names:

{
    "month": "January",
    "year": "2020",
    "workers": {
        "John": [
            {
                "days": "12",
                "shop": "Shop #1"
            }
        ],
        "Bob": [
            {
                "days": "11",
                "shop": "Shop #1"
            },
            {
                "days": "4",
                "shop": "Shop #2"
            }
        ]
    }
}

Of course I can neither know the number nor the names of the workers.

It might be simple but I can't really get to produce the template-side code to parse such data. Any tips?


Solution

  • You could use the angular-expressions package option, see here on how to install it :

    https://docxtemplater.readthedocs.io/en/latest/angular_parse.html

    Then you could do, in your code :

    expressions.filters.loopObject = function(input) {
        return Object.keys(input).map(function(key) {
                 return { key , value : input[key]};
        });
    }
    

    And in your template, you can now write :

    {#workers | loopObject}
    Name : {key}
    Shop : {value.shop}
    Days : {value.days}
    {/}