2

I'm using PHPWord to generate reports based on a template.

I replace placeholders in that template

$templateProcessor = new TemplateProcessor('template.docx');
$templateProcessor->setValue('placeholder_name', 'value5123');

and save the new file

$templateProcessor->saveAs('report.docx');

Pretty straightforward.

However, there are some values which are optional, so they leave stray placeholders behind, and the best I've been able to do is replace them with an empty string, which still leaves blank lines.

Is there a way to remove the placeholder expression altogether and prevent it (and the blank line) from showing in the final file?

Thanks

Scaramouche
  • 3,188
  • 2
  • 20
  • 46

2 Answers2

0

I know it's an old question, but an other user asked some hours ago in the comments if I found a solution. And yes, I did.

The removeTemplateVariable method can be used to remove empty placeholders, without creating a empty line. Here are the docs: https://www.phpdocx.com/api-documentation/templates/remove-template-variable

Example code:

foreach ($getVariables as $k => $v) {
    if (empty($v)) {
        $templateProcessor->removeTemplateVariable($k);
        continue;
    }

    $templateProcessor->setValue($k, $v);
}
user2933212
  • 303
  • 2
  • 4
  • 11
-1

This works for me. You can use block to do the trick. You put the placeholder into a block. Suppose that your template looks like this:

${placeholder_block}
${placeholder_value}
${/placeholder_block}

Then, in your code

// check condition if having value
if ($placeholder) {
   $templateProcessor->cloneBlock('placeholder_block', 1, true, true);
   $templateProcessor->setValue('placeholder_name', 'value5123');
}
else {
   $templateProcessor->cloneBlock('placeholder_block', 0, true, true);
}

Hope this helps you!

Stern
  • 29
  • 6