将元标签添加到 Magento 2 中的头块?如何更快更容易地做到这一点?

大家好, 

HTML 页面的 <head> 元素包含不同的元标记、JS 和 CSS 文件定义以及 JS 代码片段。在 Magento 2 中,如果您希望在 <head> 中插入元标记,则需要使用一些自定义代码片段。 

现在就开始!

在 Magento 2 的 Head Block 中添加元标记的快速指南

您需要从自定义主题创建扩展文件,以将 <meta> 标记添加到布局中的 <head> 元素中。

app/design/frontend/<Vendor>/<theme>/Magento_Theme/layout/default_head_blocks.xml.

或者您可以使用 head.additional 添加具有自定义类和自定义 phtml 的新块:

<referenceBlock name="head.additional"> <block 
class="Vendor\Module\Block\CustomHead" name="custom_head" 
template="Vendor_Module::custom_head.phtml"/> </referenceBlock>

默认类中呈现标记元\Magento\Framework\View\Page\Config\Renderer。

5 种元类型

这个类可以渲染 5 种类型的元数据并将它们全部捕获: 

  • og:是一种用于在您的网站和社交网络之间进行通信的协议。比如开放图的一些属性Og:title,Og:type,Og:description,Og:image,Og:url……
  • charset:用于指定 HTML 文档的字符编码
  • content_type:用于声明网站的语言显示代码
  • x_ua_compatible
  • media_type:用于指定要链接的元类型
  • “Default” case:使用 Magento 的默认元标记,如元标题、元描述。

尝试使用以下代码添加到您的主题布局中: 

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> 
   <head> 
    <! -- 这将创建一个类似 '<meta 
http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">' 的标签 --> 
    <meta name="x_ua_compatible" content="IE= edge,chrome=1"/> 
    <!-- 这将创建一个类似 '<meta property="og:type" 
content="article"/>'' 的标签 --> 
    <meta name="og:type" content ="article"/> 
    <!-- 这将创建一个类似 '<meta charset="UTF-8">' 的标签 --> 
    <meta name="charset" content="UTF-8"/> 
    <!-- 这将创建一个类似 '<meta http-equiv="Content-Type" 
content="content-type-value"/>' 的标签 - ->
    <meta name="content_type" content="content-type-value"/> 
    <!-- 这个标签不会渲染(详见
\Magento\Framework\View\Page\Config\Renderer) --> 
    <meta name ="media_type" content="any-value"/> 
    <!-- 这将创建一个标签,如 '<meta name="my_custom_type" 
content="my_custom_value"/>' --> 
    <meta name="my_custom_type" content ="my_custom_value"/> 
   </head> 
</page>

结论

这就是我们在 Magento 2 的 head 块中添加元标记的快速指南。