您可能已经知道,页面的 HTML<head>部分包括不同的元标记、CSS、JS 文件定义、JS 代码片段等。通常,不需要复杂的逻辑来添加一些适当的内容。然而,在各种情况下,我们需要将几个取决于系统配置的元素插入到头部。

如果您一直使用Magento 1,您会发现使用head部分的内容很容易操作。然而,在最新的 Magento 版本中,向标头添加元标记对您来说可能有点棘手。因此,在今天的文章中,我将指导您如何添加块和模板,更具体地说,如何将元标签添加到 Magento 2 的头部部分。

将元标签添加到标题

为了<meta>向布局<head>元素添加标签,您需要创建一个类似于以下内容的主题扩展文件:app/design/frontend/<Vendor>/<theme>/Magento_Theme/layout/default_head_blocks.xml

默认情况下,是呈现标签\Magento\Framework\View\Page\Config\Renderer的类。<meta>有五种类型的元,并且此类呈现包罗万象的(默认):

  • og
  • charset
  • content_type
  • x_ua_compatible
  • media_type
  • “default” case

您可以使用以下内容作为示例来包含在布局主题中:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <head>
    <!-- This will create a tag like '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">' -->
    <meta name="x_ua_compatible" content="IE=edge,chrome=1"/>
    <!-- This will create a tag like '<meta property="og:type" content="article"/>'' -->
    <meta name="og:type" content="article"/>
    <!-- This will create a tag like '<meta charset="UTF-8">' -->
    <meta name="charset" content="UTF-8"/>
    <!-- This will create a tag like '<meta http-equiv="Content-Type" content="content-type-value"/>' -->
    <meta name="content_type" content="content-type-value"/>
    <!-- This tag will not render (see \Magento\Framework\View\Page\Config\Renderer for details) -->
    <meta name="media_type" content="any-value"/>
    <!-- This will create a tag like '<meta name="my_custom_type" content="my_custom_value"/>' -->
    <meta name="my_custom_type" content="my_custom_value"/>
   </head>
</page>