I have this following code that basically renders partials. However I was trying to find a way to prevent polluting $templatePath
variable into the template (the variable is currently accessible from template which is not what I want). I only want $template
and $viewHelper
variables to be accessible in the template scope. Do you have any idea?
public function renderComponent(
string $templatePath,
ViewComponentEntityInterface $component
): string {
if (! file_exists($templatePath)) {
throw new RuntimeException('Incorrect component template path: ' . $templatePath);
}
$viewHelper = $this->viewHelperFactory->create();
ob_start();
try {
(static function (
ViewComponentEntityInterface $template,
ViewHelper $viewHelper
) use ($templatePath) {
include $templatePath;
})($component, $viewHelper);
return ob_get_clean();
} catch (Throwable $e) {
ob_end_clean();
throw $e;
}
}
I tried to find something like array_shift
but for single variable that would just unset the value and return it at the same time.
Askalot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3