该 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>