0

I want to create a Magento\Catalog\Block\Product\View block in a custom controller action (which will be used for an AJAX call later on). However I am getting the following error when creating the block (and setting the template):

Exception #0 (Magento\Framework\Exception\ValidatorException): Invalid template file: 'Vendor_Module::product.phtml' in module: 'Magento_Catalog' block's name: 'product\view_0'

app/code/Vendor/Module/Controller/Product/View.php

<?php

namespace Vendor\Module\Controller\Product;

class View extends \Magento\Catalog\Controller\Product
{
    protected $layoutFactory;
    protected $resultFactory;


    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\LayoutFactory $layoutFactory,
        \Magento\Framework\Controller\Result\RawFactory $resultFactory
    ) {
        $this->layoutFactory = $layoutFactory;
        $this->resultFactory = $resultFactory;
        parent::__construct($context);
    }


    public function execute()
    {
        $block = $this->layoutFactory->create()
                    ->createBlock('Magento\Catalog\Block\Product\View')
                    ->setTemplate('Vendor_Module::product.phtml')
                    ->toHtml();

        $result = $this->resultFactory->create();
        $result->setContents($block);

        return $result;
    }
}

app/code/Vendor/Module/view/frontend/product.phtml

<p>Hello World!</p>

app/code/Vendor/Module/etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="foo" frontName="foo">
            <module name="Vendor_Module" />
        </route>
    </router>
</config>

I can't find the mistake. The definition of the template (Vendor_Module::product.html) plus the template's location should be correct. I also tried putting the template directly in app/code/Vendor/Module/view - but that did not change anything.

What could be the problem here?

1

Simple solution: I forgot the templates subfolder in my template's path. So instead of

app/code/Vendor/Module/view/frontend/product.phtml

it should of course be

app/code/Vendor/Module/view/frontend/templates/product.phtml

| improve this answer | |
0

Try to add the template in this tree directory app/code/Vendor/Module/view/frontend/templates/product/view/product.phtml

| improve this answer | |
  • No, that did not work. That wouldn't make any sense anyway, since the template I am setting for the block is Vendor_Module::product.phtml, not Vendor_Module::product/view/product.phtml. – fritzmg Feb 14 '18 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.