I am following the 'Fundamentals of Magento 2' course and, I have to say, I am getting really frustrated with the example code being wrong on every exercise!
I am trying to set a template for a custom block within a controller. My folder structure is:
- /app/code/Training/Rendering/
-- Block/Template.php
-- Controller/Block/Template.php
-- view/frontend/template.phtml
The routes are working fine as I can print output on the page from the controller. The files mentioned above (in order) contain the following:
/app/code/Training/Rendering/Block/Template.php:
<?php
namespace Training\Rendering\Block;
/**
* Custom template block
*
* @package Training\Rendering\Block
*/
class Template extends \Magento\Framework\View\Element\Template
{
}
app/code/Training/Rendering/Controller/Block/Template.php:
<?php
namespace Training\Rendering\Controller\Block;
use Magento\Framework\App\Action\Action;
/**
* Template Action Class
* URL: testblock/Block/Template
*
* @package Training\Rendering\Controller\Block
*/
class Template extends Action
{
/**
* Execute Dispatch
*/
public function execute()
{
$block = $this->_view->getLayout()->createBlock('Training\Rendering\Block\Template');
$block->setTemplate('template.phtml');
$this->getResponse()->appendBody($block->toHtml());
}
}
app/code/Training/Rendering/view/frontend/template.phtml:
<p>Hello from custom block template!</p>
I have tried changing the controller code to
..->createBlock('Magento\Framework\View\Element\Template');
to test but no joy!
The problem is that the template (phtml) is not being loaded.
The code is exactly the same as the exercise (I tried copying and pasting from the PDF!).
I do understand that this will be handled with XML in the future, but in the interest of getting passed this exercise, I just need it to work like this.
Thanks in advance for any help.
Best Answer
First your view template file directory is wrong, You had missing templates folder in your path,
app/code/Training/Rendering/view/frontend/templates/template.phtml:
call execute function with below code, now call template like below,
$block->setTemplate('Training_Rendering::template.phtml');