Practical phpdocx

Blocks

Introduction

Blocks let you group elements and easily clone, replace and delete them. They can be created with MS Word or any other DOCX editor, even with the available methods of the phpdocx API.

Blocks can contain texts, images, placeholders to be replaced with phpdocx, sub-blocks and almost any other content.

Defining elements of the block type

To define blocks in a DOCX, create two placeholders with the same name, at the beginning and the end of the block content, with the following syntaxis:

Replace * with the block name, e.g:

When invoking block methods it is mandatory to specify the block name without neither prefix ($BLOCK by default) nor suffix. So, to delete the A1 block execute:

Replace values

Existing placeholders in a block can be replaced with phpdocx methods with no need of indicating block names. E.g., if a block has the $VAR1$ placeholder, it is possible to replace it with replaceVariableByText:

Remove and clean

The deleteTemplateBlock method deletes the whole content of a block. With this functionality it is possible to define optional blocks that can be deleted if they are unnecessary:

clearBlocks removes just the blocks placeholders while keeping their content. E.g., to replace contents and then cleaning the placeholders that wrap the blocks:

Clone

Available for Advanced and Premium licenses, cloneBlock allows to clone a block just by stating its name:

When cloning blocks, all of its content are copied. If the cloned blocks include placeholders to be replaced, the firstMatch option (available in almost all template methods) allow to iterate them to be replaced with unique values:

Tips and Tricks

The Cookbook offers several articles about blocks.

You can customize blocks prefixes with the setTemplateSymbol method.

DOCXPath lets you perform more complex replacements, such as substituting placeholders by name or its position in the block that contains them.

Next - Document transformations