I tried using the custom class for preprocessing my templates but it gave XML Dom errors and created corrupt files so I decided to just do a normal createFromTemplate, process it and then do a createDocx as I figures it probably saves the cleaned template.
Below is my code to handle caching. Note that in the folder where you keep the templates, a folder called "cache" must be created with write-access to the user running the process. Don't forget to remove the cached version of the template after making changes to the initial one. The cached files will be created at first run so the first run takes longer.
This saves quite a bit of time when replacing lots of variables.
class myProcessingClass {
private function loadTemplate($File) { // tFile is the template file
if (!is_readable($tFile)) { return null; }
$tFilePath = pathinfo($tFile);
$tFileCache = $tFilePath['dirname'] . '/cache/' . $tFilePath['filename'] . '.' . $tFilePath['extension'];
if (! file_exists($tFileCache)) {
$ret = $this->makeTemplateCache($tFile, $tFileCache);
if (! $ret) { return null; }
}
try {
return new CreateDocxFromTemplate($tFileCache, ['preprocessed' => true]);
} catch (Exception $e) {
return null;
}
}
private function makeTemplateCache($tFile, $tFileCache) {
try {
$docx = new CreateDocxFromTemplate($tFile);
$docx->processTemplate();
$docx->createDocx(str_replace(".docx", "", $tFileCache));
if (! file_exists($tFileCache)) { return false; }
return true;
} catch (Exception $e) {
return false;
}
}
}