Passing value to template using Academy example

While going through the pimcore Academy i tried this based on an example given:

Controller Action:
$this->view->somevalue = “WHY WONT THIS WORK!!!”;
return $this->render(":Example:template.html.php");

And in the template:
echo "THE VALUE IS: ";

<?= $this->somevalue?>

The result is
THE VALUE IS:

But it won’t print the value. if i change the controller to this:
return $this->render(":Example:examplelayout.html.php", array(‘somevalue’ => THIS WORKS!!!",));

The result is
THE VALUE IS: THIS WORKS!!!

Why doesn’t the $this->view->somevalue" syntax work as shown in the Academy?

Thanks!

Hi,

Please have a look at https://pimcore.com/docs/latest/Development_Documentation/MVC/Controller.html#page_Pimcore-Specialities-and-Examples
and you should get your answer here :slight_smile:

Regards
M.Ali

Thank you. I did look at the controller documentation, it gives both examples that I have tested above. But it doesn’t explain why you can use:

$this->view->foo = ‘bar’;

when you use the default template location, but this does not work if you specify the template in the controller:

$this->view->foo = ‘bar’;
return $this->render(":Default:somethingelse.html.php");

I didn’t understand why this does not work, and I must use

return $this->render(":Default:somethingelse.html.php", [“foo” => “bar”]);

instead when I specify a template. This is not explained. It even shows at the bottom of the controller documentation page:

$this->view ViewModel Used to assign variables to your view ( $this->view->foo = "bar" )

but it does not work, as you cannot access foo in the template as shown in the academy video. FYI, I’m testing on pimcore 5x if that makes a difference.

I understand your question now.
Unfortunately, I do not have an answer to your question :thinking:

I really hope someone else could answer your interesting question. :smiley:

It doesn’t make a difference.

See, this is a Symfony thing rather than Pimcore thing. When you extend Pimcore’s FrontendController, it already has built-in syntax to pass variables to the default template in the Resources/views/Controller/actionName.html.twig|php (Supposing your view is named ControllerController::actionNameAction) using the $this->view->variable syntax (renderTemplate function in the FrontendController).

Otherwise, if you tell the Action to render a specific template, this template will not, by default, get any parameters passed onto it. Because you’re overriding the $this->view->variable syntax by adding the return value BEFORE the FrontendController can return Pimcore’s default rendered template.

For more info, please have a read here: https://symfony.com/doc/current/controller.html#rendering-templates and here: https://symfony.com/doc/current/templates.html#template-variables

2 Likes

This is starting to make sense. Thank you.