Forum


Replies: 2   Views: 89
Recursively replace a variable in a template that is loaded from an external file

Posted by mybuh  · 25-02-2025 - 06:50

I load a template and replace a variable from an external file in it. The external file also contains this variable, but I can't replace it again.
Code example:
$docx = new \CreateDocxFromTemplate('nds.docx');
$docx->setTemplateSymbol('[', ']');
$docx->replaceVariableByExternalFile(['nds_cert' => 'nds2.docx'], ['matchSource' => true]);
$docx->replaceVariableByText(['nds_cert' => 'bbb '], ["firstMatch" => false]);
$docx->CreateDocx('nds3.docx');
File contents.
nds.docx:
[nds_cert]


nds2.docx:
Aaaa
[nds_cert]

I get the output
nds3.docx:
Aaaa
[nds_cert]

How to get in the file nds3.docx
Aaaa
bbb

?

Posted by admin  · 25-02-2025 - 07:05

Hello,

Please note that template methods don't replace variables added in embedded documents.
To accomplish the requested task, you need to replace the variables in the document to be embedded and then embed it:

$docx = new \CreateDocxFromTemplate('nds2.docx');
$docx->setTemplateSymbol('[', ']');
$docx->replaceVariableByText(['nds_cert' => 'bbb '], ["firstMatch" => false]);
$docx->createDocx('nds2_upd.docx');

$docx = new \CreateDocxFromTemplate('nds.docx');
$docx->setTemplateSymbol('[', ']');
$docx->replaceVariableByExternalFile(['nds_cert' => 'nds2_upd.docx'], ['matchSource' => true]);
$docx->CreateDocx('nds3.docx');

Or use mergeDocxmergeDocxAt, or importContents methods to import the contents from the document as regular content instead of as an embedded document. Using these methods you can use template methods to replace variables after merging/importing the contents.

Regards.

Posted by mybuh  · 25-02-2025 - 08:27

Thank you for answer.  Problem solved.