9阅网

您现在的位置是:首页 > 知识 > 正文

知识

content-management-system - 我如何在Magento 2中添加自定义JSON代码?

admin2022-10-28知识23

我正在与一家公司合作,使用Magento 2作为他们的CMS。

他们想在他们网站的不同页面上添加schema.org标记。

理想情况下,我想使用JSON来添加。我将创建必要的JSON代码,然后将其添加到他们网站的某个页面的头部部分。

是否可以在Magento 2中添加自定义代码到不同的页面?如果可以,是如何做到的?



【回答】:

要做到这一点,你需要添加一个定制的 phtml 模板文件在所有页面的头部,需要检查每个页面类型。所以你可以为不同的页面添加自己的自定义逻辑。请按照以下步骤进行操作。

第一步:在这里创建你的自定义模板文件 app/design/frontend/{Package}/{theme}/Magento_Theme/templates/html/custom_codes.phtml

<?php
    $getLayoutHandle = $this->getRequest()->getFullActionName(); // it returns all kind of pages handlers. just check and use by the following ways.
?>
<?php if($getLayoutHandle == 'cms_index_index'): ?>
    <!-- home page scripts here -->
<?php endif; ?>
<?php if($getLayoutHandle == 'catalog_category_view'): ?>
    <!-- product listing page scripts here -->
<?php endif; ?>
<?php if($getLayoutHandle == 'catalog_product_view'): ?>
    <!-- product details page scripts here -->
<?php endif; ?>

第二步:使用default.xml添加到上述文件的头部。app/design/frontend/{Package}/{theme}/Magento_Theme/layout/default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="head.additional">
            <block class="Magento\Framework\View\Element\Template" name="custom_codes" template="Magento_Theme::html/custom_codes.phtml"/>
        </referenceBlock>
    </body>
</page>