magento2 邮件模板中直接调用 block文件
有些邮件模板我们想直接写在phtml里面
好想法
示例
{{block class="Magento\Framework\View\Element\Template" order=$order name="order_sms" template="[vendor]_[module]::[filename].phtml" area="frontend"}}
介绍
class 必写 固定 Magento\Framework\View\Element\Template
template 文件模板 后面是文件的具体路径 Magento_Email::ces.phtml
Magento_Email/templates/ces.phtml
文件必须放在templates 文件夹下面
默认简写了 templates
area frontend 或者 adminhtml 前后端的意思
order name 是传递给phtml的数据
可以通过
$order = $this->getData('order');
在phtml获取
示例
{{block class="Magento\Framework\View\Element\Template" name="order_sms" template="Magento_Email::ces.phtml" area="frontend"}}
注意
magento2 有的版本有bug
block 传值只能传 string类型 数组或者对象传递有问题 有的传不过去 获取的是NULL 例如上面的 order=$order
所以优化
{{block class="Magento\Framework\View\Element\Template" area='frontend' template='Magento_Email::order/new_order/us/new_header.phtml' order_id=$order_id }}
订单数据的话 可以只传递 order_id
然后再对应的phtml中使用一下方法获取数据
$blockData = $this->getData();
$orderId = $blockData["order_id"];
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_order = $objectManager->create('Magento\Sales\Api\Data\OrderInterface')->load($orderId);
var_dump($_order->getData());
有讨论说更改 https://github.com/magento/magento2/issues/26882
email_template 数据表 对应的数据的 is_legacy 将0变成1
但是我是使用magento2.4 获取order 直接白屏了 没有效果
你们可以自己试下
官方邮件文档 https://devdocs.magento.com/guides/v2.4/frontend-dev-guide/templates/template-email.html
迁移自定义电子邮件模板 https://devdocs.magento.com/guides/v2.4/frontend-dev-guide/templates/template-email-migration.html
感谢 https://magento.stackexchange.com/questions/134947/magento-2-how-to-call-block-file-in-order-email-with-order-variable
感谢 https://gordonlesti.com/magento-2-email-template-block-directives/