Magento 2中如何在$block->getHtml()返回的HTML内注入标签
问题描述
我在Magento 2模板中使用$block->getItemHtml($_item)方法,该方法返回如下HTML结构:
<tr> <td class="item-info" style="font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; vertical-align: top;"> <p class="product-name" style="margin-top: 0; margin-bottom: 10px;">Crown Summit Backpack</p> <p class="sku" style="margin-top: 0; margin-bottom: 10px;">Artikuls: 24-MB03</p> </td> <td class="item-qty" style="font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; vertical-align: top;">1</td> <td class="item-price" style="font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; vertical-align: top;"> <span class="price">30,00 €</span> </td> </tr>
我希望在第一个<td class="item-info">标签内部注入自定义<p>标签,当前我的代码如下:
<?php foreach ($_invoice->getAllItems() as $_item) : ?> <?php if (!$_item->getOrderItem()->getParentItem()) : ?> <tbody> <?= $block->getItemHtml($_item); ?> <p> <?= $_item->getOrderItem()['manufacturers_code'];?> <?= $_item->getOrderItem()['initial_delivery_date']; ?> <?= $_item->getOrderItem()['qty_invoiced']; ?> <?= $_item->getOrderItem()['base_price']; ?> </p> </tbody> <?php endif; ?> <?php endforeach; ?>
请问该如何实现这一需求?
解决方案
方法一:重写项目模板(推荐)
getItemHtml()本质是调用对应区块的模板生成HTML,最规范的做法是重写该模板,直接在目标标签内添加内容:
- 定位原模板文件:发票页面的项目模板通常是
vendor/magento/module-sales/view/frontend/templates/order/items/invoice/default.phtml - 在你的主题目录下创建对应路径的模板文件:
app/design/frontend/[你的主题包]/[主题名]/Magento_Sales/templates/order/items/invoice/default.phtml - 复制原模板内容到新文件,找到
<td class="item-info">标签,在其中插入自定义<p>标签:
<td class="item-info" style="font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; vertical-align: top;"> <p class="product-name" style="margin-top: 0; margin-bottom: 10px;"><?= $block->escapeHtml($_item->getName()) ?></p> <p class="sku" style="margin-top: 0; margin-bottom: 10px;"><?= /* @noEscape */ __('Artikuls: %1', $block->escapeHtml($_item->getSku())) ?></p> <!-- 自定义内容 --> <p class="custom-item-details"> <?= $_item->getOrderItem()->getManufacturersCode(); ?> <?= $_item->getOrderItem()->getInitialDeliveryDate(); ?> <?= $_item->getOrderItem()->getQtyInvoiced(); ?> <?= $_item->getOrderItem()->getBasePrice(); ?> </p> </td>
- 清理Magento缓存,刷新页面即可生效。
方法二:字符串替换(临时应急方案)
如果不想重写模板,可通过字符串替换将自定义内容插入到目标标签内:
<?php foreach ($_invoice->getAllItems() as $_item) : ?> <?php if (!$_item->getOrderItem()->getParentItem()) : ?> <tbody> <?php $itemHtml = $block->getItemHtml($_item); // 构造自定义内容 $customContent = '<p>' . $_item->getOrderItem()->getManufacturersCode() . $_item->getOrderItem()->getInitialDeliveryDate() . $_item->getOrderItem()->getQtyInvoiced() . $_item->getOrderItem()->getBasePrice() . '</p>'; // 替换第一个</td>标签,将自定义内容插入到item-info的td内部 $modifiedHtml = str_replace('</td>', $customContent . '</td>', $itemHtml, 1); echo $modifiedHtml; ?> </tbody> <?php endif; ?> <?php endforeach; ?>
注意:该方法依赖HTML结构的稳定性,若Magento更新模板结构可能失效,优先使用方法一。
内容的提问来源于stack exchange,提问作者LosMos
相关产品推荐
相关产品推荐

