Magento 2 如何从block块文件中直接调用phtml模板文件
无需Layout XML配置,Block中直接调用phtml模板的实现方案(适用于Magento 2 环境)
- 方案1:重写自定义Block的
_toHtml()方法绑定模板
你可以在自定义Block类中重写_toHtml方法,直接指定模板路径完成渲染,无需在XML文件中提前配置模板绑定关系,代码示例如下:
<?php namespace Vendor\YourModule\Block; use Magento\Framework\View\Element\Template; class YourCustomBlock extends Template { protected function _toHtml() { // 模板路径规则:Vendor_ModuleName::模板相对路径/文件名.phtml $this->setTemplate('Vendor_YourModule::custom/demo.phtml'); return parent::_toHtml(); } }
模板文件需放置在模块对应视图目录下,前端场景路径为
app/code/Vendor/YourModule/view/frontend/templates/custom/demo.phtml,后台场景替换为view/adminhtml路径即可。
- 方案2:Block中动态渲染任意phtml模板
如果需要在现有Block中动态调用其他phtml模板输出内容,可直接调用布局实例创建临时Template块后渲染,示例如下:
// 生成模板渲染后的HTML内容 $renderedHtml = $this->getLayout() ->createBlock(\Magento\Framework\View\Element\Template::class) // 传入模板所需参数 ->setData('custom_var', '自定义传递参数') ->setTemplate('Vendor_YourModule::other/template.phtml') ->toHtml(); // 可直接返回该内容输出,或拼接其他内容后返回 return $renderedHtml;
模板中可直接通过
$block->getCustomVar()获取传入的参数值。
内容的提问来源于stack exchange,提问作者Ekta Rathod
相关产品推荐
相关产品推荐

