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 template 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, replace and clean

The deleteBlock 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:

By default, deleteBlock removes the block contents including paragraphs. Inline block contents can be removed setting the type option as inline:

replaceBlock replaces a block content with a new string or WordFragment content. E.g., to replace a block with a string and another block with a WordFragment:

clearBlocks removes just the blocks placeholders while keeping their content. E.g., to replace contents and then clean 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 contents are copied. If the cloned blocks include placeholders, the same method can replace them:

The firstMatch option (available in almost all template methods) can also be used to iterate the placeholders to be replaced by new values:

On Clone blocks replacing placeholders there are samples to illustrate replacing placeholders when cloning blocks.

Tips and Tricks

The Cookbook offers several articles about blocks.

You can customize blocks prefixes and the characters to wrap them with setTemplateBlockSymbol and setTemplateSymbol methods.

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