resources 组件可以创建新变量、添加标头并将资源注入到页面。resources 组件可以在任何页面、布局或局部视图上使用。
该组件支持以下属性。
| Property | Description |
|---|---|
| js | Array of JavaScript files in the theme assets/js folder |
| less | Array of LESS files in the theme assets/less folder |
| scss | Array of SCSS files in the theme assets/scss folder |
| css | Array of Stylesheet files in the theme assets/css folder |
| vars | Includes variables available on the page or layout. |
| headers | Includes headers with the page response. |
以下示例使用 vars 属性来创建一个名为 activeNav 的新变量并且此变量可用于页面生命周期,这包括该页面的布局或页面上使用的局部视图。该变量通过 {{ activeNav }} Twig 变量访问。
[resources]
vars[activeNav] = 'blog'{% if activeNav == 'blog' %}
<p>The blog is active!</p>
{% endif %}资源组件允许您在页面上定义任意数量的变量。这些变量将作为普通的 Twig 变量供布局使用。
[resources]
vars[activeNav] = 'blog'您也可以使用页面周期中的参数。在以下示例中,activeNav 变量将包含在 :slug 页面路由中找到的值。
url = "mypage/:slug"
[resources]
vars[activeNav] = '{{ :slug }}'此概念也适用于组件变量。 以下示例通过页面路由中的 :slug 查找作者然后将 author.id 赋值给 authorIdPage 页面变量。
url = "/author/:slug"
[section author]
handle = "Blog\Author"
identifier = "slug"
[resources]
vars[authorIdPage] = 'Author ID is: {{ author.id }}'如果布局包含标准 {% scripts %} 和 {% styles %} 标签,那么就可以将资产注入到这些占位符中。这些资产将被捆绑并组合成一个单一的脚本/样式引用。
使用资源组件加载的资产应位于主题内的一个特定文件夹中,如可用属性中所述。一个例子可能是一个名为 blocks/carousel.htm 的局部文件
[resources]
css[] = "blocks/carousel.css"
scss[] = "blocks/carousel.scss"
less[] = "blocks/carousel.less"
js[] = "blocks/carousel.js"<!-- Carousel Contents Here -->现在当局部文件加载到页面时,脚本和样式表将被注入到布局中。这些资产文件应分别位于 assets/js/blocks/carousel.js 和 assets/less/blocks/carousel.less 目录中。
<!-- Assets for the carousel are injected automatically -->
{% partial 'blocks/carousel' %}在页面上使用两次该局部文件只会注入一次资源。
作为一个定义自定义标头的例子,您可能希望在页面上渲染 XML 内容而不是 HTML 内容。这可以通过向页面注入一个 Content-Type 标头并给它一个 text/xml 的值来实现。当页面加载时,此标头值将随响应一同发送。
url = "/blog/rss"
[resources]
headers[Content-Type] = 'text/xml'<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<!-- RSS contents here -->
</rss>