magento2布局layout-引入静态资源js,css

7天成为Magento系统架构师,现在开始学习Magento全栈开发!

《Magento2.X企业级开发实战》

magento2布局layout-引入静态资源js,css

引入静态资源(JavaScript、CSS、字体)
JavaScript、CSS 和其他静态资源添加到页面配置文件的 部分。 Magento 商店页面 的默认外观由 app/code/Magento/Theme/view/frontend/layout/default_head_blocks.xml 定义。 添加 CSS 和 JavaScript 的推荐方法是在您的自定义主题中扩展此文件,并在那里添加资产。 以下文件是您必须添加的文件示例:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <head>
    <!-- Add local styles resources -->
    <css src="css/my-styles.css" />
    <css src="<Namespace>_<Module>::css/custom-styles.css" />

    <!-- The following two ways to add local JavaScript files are equal -->
    <script src="Magento_Catalog::js/sample1.js" />
    <script src="Magento_Catalog/js/sample1.js" />

    <!-- Magento support async or defer attribute in script tag -->
    <script async="" src="Magento_Catalog::js/sample1.js" />
    <script defer="" src="Magento_Catalog::js/sample1.js" />

    <link src="js/sample.js" />
    <link src="sample.js" />

    <!-- Add external resources -->
    <css src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" src_type="url" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" src_type="url" />
    <link rel="stylesheet" type="text/css" src="http://fonts.googleapis.com/css?family=Montserrat" src_type="url" />
  </head>
</page>

添加外部资源时,必须指定 src_type=”url” 参数值。
您可以使用 <link src=”js/sample.js”/> 或 <script src=”js/sample.js”/> 指令将本地存储的 JavaScript 文件添加到您的主题。这样,javascript 文件的路径将是 <theme_dir>/web/js/sample.js。如果我们使用 <link src=”sample.js”/>,Magento 将在 <theme_dir>/web/sample.js 获取 javascript 文件
资产的路径是相对于以下位置之一指定的:
CSS 和 LESS 文件存储在 <theme_dir>/web/css/ 目录中。与字体相关的文件存储在 <theme_dir>/<Namespace>_<Module>/web/fonts/ 目录中。静态资产(例如图像)存储在 <theme_dir>/<Namespace>_<Module>/web/images/ 目录中。JS 文件存储在 <theme_dir>/<Namespace>_<Module>/web/js/ 目录中。添加条件注释条件注释旨在为 Internet Explorer 提供特殊说明。在添加资产方面,您可以为特定版本的 Internet Explorer 添加要包含的 CSS 文件。示例如下:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <head>
    <css src="css/ie-9.css" ie_condition="IE 9" />
  </head>
</page>

这会在生成的 HTML 中添加 IE 条件注释,如下例所示:

<!--[if IE 9]>
<link rel="stylesheet" type="text/css" media="all" href="<your_store_web_address>/pub/static/frontend/ExampleCorp/orange/en_US/css/ie-9.css" />
<![endif]-->
如无特殊说明或标注,任何个人或组织,复制、转载、采集本站内容请注明:
本文来源于:【Magento中文网】,并添加本文地址链接。
如未按上述操作复制或转载,本站有权追究法律责任。
若本站内容侵犯了原著者的合法权益,可联系我们进行处理。