open-xml-templating/docxtemplater

Conditional assignment doesn't work as expected

ammyt opened this issue · 1 comments

Hi, in my template I am trying to do the following:
{@email = profileName.includes('guest') ? 'info@dx.com' : 'support@dx.com'}
My templateData contains { profileName: 'site guest' }.

However, this doesn't seem to work as I always end up with 'support@dx.com'.

I noticed the ternary example in: https://docxtemplater.com/docs/angular-parse/
{#cond4 ? users : usersWithAdminRights}
Paragraph 3
{/}
However, it doesn't make sense to me. What exactly does this do? It checks cond4 and then determines users or usersWithAdminRights, but what exactly happens to users or usersWithAdminRights? In the end 'Paragraph 3' will always be rendered either ways?

So I am now kind of stuck on figuring out how to use ternaries.

Hello @ammyt

That is becasue with the angular parser, javascript expressions like ("includes") do not work.

You have to instead use custom filters, like this :

{@email = (profileName | includes:guest) ? '[info@dx.com](mailto:info@dx.com)' : '[support@dx.com](mailto:support@dx.com)'}

And in your code, write :

const expressionParser = require("docxtemplater/expressions.js");
expressionParser.filters.includes = function (input,search) {
    // 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.includes(search);
};
new Docxtemplater(zip, { parser: expressionParser });

However, I would advise you to do those kind of initialization inside your code, not inside your template, since the template will start to grow and grow over time if you allow it to contain code.