I'm trying to add custom template from my custom module.
Layout file: app/code/Foo/Bar/view/frontend/layout/default.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="footer">
<block class="Foo\Bar\Block\FooterTest" name="footer_assets" template="footer/test.phtml" />
</referenceContainer>
</body>
</page>
my template: app/code/Foo/Bar/view/frontend/templates/footer/test.phtml
<span>test</span>
When i rename layout file from default.xml to cms_index_index.xml then template is displayed, but only on home page. What i have to change to display this template on all pages?
5 Answers 5
In you default.xml you can add after="footer_links" and mention your module template like "Foo_Bar::footer/test.phtml"
I have tried below code and working fine for me.
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="footer">
<block class="Foo\Bar\Block\FooterTest" name="footer_assets" after="footer_links" template="Foo_Bar::footer/test.phtml"/>
</referenceContainer>
</body>
</page>
Hope this answer will help.
Change default.xml
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="footer"> <block class="Foo\Bar\Block\FooterTest" name="footer_assets" template="Foo_Bar::footer/test.phtml" /> </referenceContainer> </body> </page>
And make sure your block class is [Foo\Bar\Block\FooterTest.php]
namespace Foo\Bar\Block;
class FooterTest extends \Magento\Framework\View\Element\Template
{
}
@krishna ijjada @Sohel Rana thx for help but cause was in another place. First i tried add this template in my custom theme and then i was added it by module. When i removed it from default.xml in theme then it has been started work by my module.
Maybe you can make it work certainly in controller/action class example View.php with execute() method return block and layout specific.try this with may example :
`<?php
declare(strict_types=1);
namespace MageMastery\FirstLayout\Controller\Page;
use Magento\Framework\App\Action\Action; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\View\Result\Page;
class View extends Action { public function execute() { /** @var Page $resultPage */ // var_dump($this->resultFactory->create(ResultFactory::TYPE_PAGE)); $page = $this->resultFactory->create(ResultFactory::TYPE_PAGE); $block = $page->getLayout('default')->getBlock('magemastery.first.layout.example.custom'); $block->setData('custom-param', 'Data from Controller'); return $page; }
} `
Please create a file like below structure for proper out.
view/adminhtml/layout/routeid_controller_index.xml