Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Access index inside a loop #397

Closed
jorgeas80 opened this issue Apr 24, 2018 · 2 comments
Closed

Access index inside a loop #397

jorgeas80 opened this issue Apr 24, 2018 · 2 comments
Labels

Comments

@jorgeas80
Copy link

jorgeas80 commented Apr 24, 2018

Dear devs,

Is there any way to access the index inside of a loop? Like AngularJS $index.

Use case:

This data

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

And this template, or something similar

{#products} 
{$index} - {.} 
{/products}

To generate this

1 - Windows
2 - Mac OSX
3 - Ubuntu

Of course, I could generate the index along with the data, but I'd like to handle it at template level, if possible, not at data level.

@edi9999
Copy link
Member

edi9999 commented Apr 28, 2018

Edited Answer, from November 2022 :

This answer requires docxtemplater 3.32.3 or later.

You can first install angular-expressions : by running : npm install --save angular-expressions

Then in your code, use the following :

const expressionParser = require("docxtemplater/expressions.js");
new Docxtemplater(zip, { parser: expressionParser });

This will allow tags such as {$index}, {$index === 0} , {$index + 1} , ...

Old Answer (2018), does not work as well

This is possible with version 3.6.2 (released a few minutes ago).

To do it , use following code :

function parser(tag) {
    return {
        get(scope, context) {
            if (tag === "$index") {
                const indexes = context.scopePathItem;
                return indexes[indexes.length - 1];
            }
            return scope[tag];
        },
    };
}
const doc = new Docxtemplater(zip, {parser});
doc.setData({});
doc.render();
const buffer = doc.getZip();

See https://docxtemplater.readthedocs.io/en/latest/configuration.html#custom-parser for full documentation.

However, with this solution, things such as {$index + 1} or other calcutions don't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants
@jorgeas80 @edi9999 and others