1

I am getting stated using DocxTemplater with Node.

I am trying to figure out how to remove an empty line if the element is empty (i.e '' or null) - I can't seem to find a similar case on SO or elsewhere!

My Placeholders on the Docx look like this:

{#data}
{#input}
{Line1}
{Line2}
{Line3}
{/input}
{/data}

Any my Array looks like this:

data: {
    input: {
        Line1: 'TEXT1',
        Line2: '',
        Line3: 'TEXT3'
    },
}

When I create a document I would like to remove the line in which 'Line2' is as its empty.

So instead of this:

TEXT1

TEXT3

I would like

TEXT1
TEXT3

UPDATE

Changed my code to the below as per the advice, however haven't had any success. Any more pointers? Thanks in advance!

{#data}
{#input}
{#Line1}{Line1}{/Line1}
    {#hasLine2}{Line2}{/hasLine2}
    {#Line3}{Line3}{/Line3}
{/input}
{/data}

And

data: {
    input: {
        Line1: 'TEXT1',
        Line2: '',
        Line3: 'TEXT3',
        hasLine2: false
    },
}
tbowden
  • 1,008
  • 1
  • 19
  • 44

2 Answers2

3

I'm the creator of docxtemplater

You can do like this :

{#data}
{#input}
{#Line1}
{Line1}
{/Line1}
{#hasLine2}
{Line2}
{/hasLine2}
{#Line3}
{Line3}
{/Line3}
{/input}
{/data}

and you in your code :

new Docxtemplater(zip, {paragraphLoop:true})

With the paragraphLoop option, if the start of the loop and the end of the loop are on separate paragraphs, then you won't get any extra space when your sections are empty.

This is documented here : https://docxtemplater.com/docs/configuration/#paragraphloop

edi9999
  • 19,701
  • 13
  • 88
  • 127
0

Apperantly In docxtemplater, conditions and loops use the same syntax called Sections.

So you can make the template like:

{#data}
  {#input}
    {#Line1}{.}{/Line1}
    {#Line2}{.}{/Line2}
    {#Line3}{.}{/Line3}
  {/input}
{/data}
Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
  • Thanks, forgot to add I've tried this before and couldn't get it to work! Is there something else I maybe missing? – tbowden Jul 08 '19 at 18:50
  • Maybe you should make keys for these lines, and make them boolean. Like `hasLine1` and so on. and use `{#hasLine1}{line1}{/hasLine1}` – Aritra Chakraborty Jul 08 '19 at 18:51
  • Thanks Arita, I have amended my answers to reflect your advice. Do you have an other pointers? Thanks! – tbowden Jul 09 '19 at 09:26