Forum


Replies: 3   Views: 1574
How can i scope template replacements within a block?
Topic closed:
Please note this is an old forum thread. Information in this post may be out-to-date and/or erroneous.
Every phpdocx version includes new features and improvements. Previously unsupported features may have been added to newer releases, or past issues may have been corrected.
We encourage you to download the current phpdocx version and check the Documentation available.

Posted by admin  · 09-07-2021 - 06:37

Hello,

The replaceVariableByText method (and other template methods) does replacements in the whole target. As you say, you can use the firstMatch option to replace only the first occurrence and iterate placeholders with the same name by their specific new values.

You can use the firstMatch option to do replacements after cloning blocks, or use the $variablesBlock option available in cloneBlock. Please check the information available at https://www.phpdocx.com/documentation/snippets/clone-blocks-replacing-placeholders, which details both approaches.

The "occurrence" option available in cloneBlock is very useful for working with subblocks (nested blocks).

As an alternative approach, you could also use replaceWordContent available in DOCXPath to do complex replacements. Using this method, you can do almost any kind of replacements, for example: the second occurrence of a paragraph that contains $VAR$, or the placeholder that its paragraph also contains other text content, or more advanced replacements such as the third occurrence of a placeholder that is inside the second occurrence of a specific block. DOCXPath allows working with the internal options and also custom XPath queries.

For further support, please send to contact[at]phpdocx.com a DOCX template sample and the DOCX output you'd like to get; the dev team will check them. We'll generate and send a custom script using them.

Regards.