Magento 2 信件樣板詳解(二) -在 Template 內插入 block 應用

Template 是 html 檔 無法執行如迴圈或是判斷式之類的程式邏輯,若有這方面的需求就必須要用到插入 block 的技巧,所幸原生程式裡就有 block 的應用可以讓我們參考。
參考檔案 : vendor/magento/module-sales/view/frontend/email/shipment_new.html
可以看到內容有一段
{{block class='Magento\\Framework\\View\\Element\\Template' area='frontend' template='Magento_Sales::email/shipment/track.phtml' shipment=$shipment order=$order}}
其中 class=’Magento\\Framework\\View\\Element\\Template’ 的設定是沒作用的但卻不能省略,若有需要可以自訂 class 並 extends \Magento\Framework\View\Element\Template
template=’Magento_Sales::email/shipment/track.phtml’
指定使用的檔案為:vendor\magento\module-sales\view\frontend\templates\email\shipment\track.phtml
shipment=$shipment 是指帶入變數 $shipment 變數名稱為 shipment
order=$order 一樣是帶入變數
接下來我們參考 Magento 的程式 自己來寫一個 Block
php pestle.phar generate_module AstralWeb EmailBlock 0.0.1
並建立一個 template 檔案 app/code/AstralWeb/EmailBlock/view/frontend/templates/email/template.phtml
<?php
$_order = $block->getOrder();
$items = $_order->getItems();
?>
<?php if ($_order) : ?>
<table class="shipment-track">
<thead>
<tr>
<th>Sku</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php foreach( $items as $item ){ ?>
<tr>
<td><?php echo $item->getSku(); ?>:</td>
<td><?php echo $item->getName(); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php endif;
這 template 目的是將訂單內項目都列出來,可以看到這 template 會需要用到 order 這變數。
block 呼叫的方式為
{{block class='Magento\\Framework\\View\\Element\\Template' area='frontend' template='AstralWeb_EmailBlock::email/template.phtml' order=$order}}
將上述那段 block 直接放入 order_new.html 內(請參考 Magento 2 信件樣板詳解(一)覆寫樣版),接下來就直接寄信看看。
可以看到訂單內容這樣就是完成了。
block 的設計可以補足 template 不能使用邏輯判斷的缺點,也可以重複使用(雖然不太容易有這樣的需求),總而言之算是相當方便的功能。
以上是本篇對如何在Magento 2 設定電子報的介紹,如果有您有更多疑問可以詢問我們,未來會撰寫更多電商網站相關文章,您想知道什麼嗎?歡迎在下方留言給我們。或追蹤我們的粉絲專頁,就不錯過最新文章喔!
我要留言