Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

Magento 2:如何从phtml文件调用任何模板块?

Magento 1.x中,您可以使用以下代码在任何其他模板(phtml)文件中调用/打印任何模块的模板块:

echo $this->getLayout()
          ->createBlock('newmodule/newblock')
          ->setTemplate('newmodule/newblock.phtml')
          ->toHtml();

Magento 2.x中,它略有不同。

以下是在Magento 2的另一个模板文件中调用/打印自定义模板块的代码

假设您要调用模块Chapagain_HelloWorld的模板块(helloworld.phtml),则应编写以下代码:

echo $this->getLayout()
          ->createBlock('Chapagain\HelloWorld\Block\HelloWorld')
          ->setTemplate('Chapagain_HelloWorld::helloworld.phtml')
          ->toHtml();

如果要在CMS静态块或Magento 2的CMS页面中调用模板块,则只需编写以下代码:

让我们以上面相同的示例为例(调用模块Chapagain_HelloWorld的helloworld.phtml)。

{{block class="Chapagain\HelloWorld\Block\HelloWorld" name="your_block_name" template="Chapagain_HelloWorld::helloworld.phtml"}}

将变量或参数传递给块

您还可以在从CMS页面或静态块调用.phtml模板时传递变量或参数。

{{block class="Chapagain\HelloWorld\Block\HelloWorld" name="your_block_name" title="My Title" count="10" template="Chapagain_HelloWorld::helloworld.phtml"}}

您可以在上面看到我们已经向块代码传递了两个额外的变量/参数(titlecount)。

现在,要从模板(.phtml)或块类(.php)文件访问这些变量,您必须编写以下内容。

$title = $this->getData('title');
$count = $this->getData('count');

对于本文的示例,此代码可以同时写在template(Chapagain\HelloWorld\view\frontend\templates\helloworld.phtml)和block class(Chapagain\HelloWorld\Block\HelloWorld.php)文件中。

希望这可以帮助。谢谢。

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论