Forum


Replies: 2   Views: 176
How do i check if a block has variables?
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 crewscontrol  · 19-12-2023 - 15:45

I am using the getTemplateVariables method to get a list of variables.  I can check if the variable starts with  "BLOCK_" to know which ones are blocks but would like to know if the block has variables inside.  I want to keep track of variables that are blocks that contain other variables and those that do not.

 

Is there a way to do this?  Thanks.

Posted by admin  · 19-12-2023 - 16:54

Hello,

There's no direct method to get the list of variables inside a block.

As getTemplateVariables parses the variables in a document in order, an approach would be iterating the variables to check when a block starts and ends to get the variables inside it.

For example:

$docx = new CreateDocxFromTemplate('template.docx');
$variables = $docx->getTemplateVariables();

$variablesBlock = [];
$blockStart = false;
$blockPlacehoderName = '';
foreach ($variables['document'] as $variable) {
    // check if the variable is a block placeholder
    if (strpos($variable, $docx->getTemplateBlockSymbol()) !== false) {
        $blockStart = !$blockStart;
        $blockPlacehoderName = $variable;
        if (!isset($variablesBlock[$blockPlacehoderName])) {
            $variablesBlock[$blockPlacehoderName] = [];
        }
    }

    // if the variable is in a block placeholder and it isn't a block placeholder, add it to the array
    if ($blockStart && strpos($variable, $docx->getTemplateBlockSymbol()) === false) {
        $variablesBlock[$blockPlacehoderName][] = $variable;
    }
}

print_r($variablesBlock);

This sample code generates a new array with the block placeholders as array keys and the variables as values.

Regards.

Posted by crewscontrol  · 19-12-2023 - 20:36

Thank you, I'll give it a try.