Nested Shortcode for foreach loop
Closed this issue · 2 comments
vish4395 commented
Hello, I have a problem. I need to show the contents of the array using foreach()
with the shortcode, like:
[customers]
Name - [cust_name]
Contact - [cust_contact]
[/customers]
How I can achieve this? Please help me. Thanks.
thunderer commented
Hi @vish4395, any parent shortcode controls the processing of its children, therefore you can do it this way:
$customers = [
['id' => 1, 'name' => 'X', 'contact' => 'XC'],
['id' => 2, 'name' => 'Y', 'contact' => 'YC'],
];
$text = <<<EOF
[customers]
ID: [id /]
Name: [name /]
Contact: [contact /]
[/customers]';
EOF;
$handlers = new HandlerContainer();
$handlers->add('customers', function(ProcessedShortcode $shortcode) use($customers) {
$result = '';
foreach($customers as $customer) {
$handlers = new HandlerContainer();
$handlers->add('id', fn() => $customer['id']);
$handlers->add('name', fn() => $customer['name']);
$handlers->add('contact', fn() => $customer['contact']);
$processor = new Processor(new RegularParser(), $handlers);
$result .= $processor->process($shortcode->getTextContent());
}
return $result;
});
$processor = new Processor(new RegularParser(), $handlers);
var_dump($processor->process($text));
vish4395 commented