tinydots / craft-front-matter
从twig模板中提取YAML数据
Requires
- craftcms/cms: ^3.0.0
- mnapoli/front-yaml: ^1.6
Requires (Dev)
- codeception/codeception: 2.4.x-dev
This package is auto-updated.
Last update: 2024-09-07 01:02:57 UTC
README
Front Matter 允许您从twig模板顶部的特殊格式注释中提取YAML数据。这对于在Craft CMS项目中包含样式库特别有用。
要求
此插件需要Craft CMS 3.0.0或更高版本。
安装
要安装此插件,请按照以下说明操作。
-
打开您的终端并转到您的Craft项目
cd /path/to/project
-
然后让Composer加载插件
composer require tinydots/craft-front-matter
-
在控制面板中,转到设置 -> 插件,然后点击Front Matter的“安装”按钮。
使用方法
定义数据
您可以通过使用{#---
和---#}
标签将YAML元数据添加到任何twig模板的顶部。因为YAML数据在twig注释内,所以您仍然可以正常使用{% include %}
和{% embed %}
模板,无论是否安装了此插件。
给定一个用于渲染链接的_components/link.html
模板,具有以下YAML前缀数据
{#--- title: Link description: > This is a tiny component for rendering a single link. {% include "_components/link" with { url: 'https://www.google.com', text: 'Google', } %} variables: text: The text to use as the body of the link url: The url of the target examples: - text: Craft CMS url: https://www.craftcms.com - text: Google url: https://www.google.com ---#} <a href="{{ url }}">{{ text }}</a>
访问数据
您可以使用craft.frontMatter.parse(template)
从其他模板以数组形式访问YAML数据
{% set component = craft.frontMatter.parse("_components/link") %} <h2>{{ component.title }}</h2> {{ component.description|markdown }}
样式库
将YAML数据嵌入模板的主要用例是在Craft项目中创建样式指南或样式库。
集合/数组可以正常使用,因此可以用来记录模板接受的变量
{% if component.variables is defined %} <h3>Variables</h3> <dl> {% for variable, description in component.variables %} <dt><code>{{ variable }}</code></dt> <dd>{{ description|markdown }}</dd> {% endfor %} </dl> {% endif %}
您可以使用craft.frontMatter.source(template)
输出模板的转义源代码,而不包括YAML数据
<h3>Source code</h3> <pre> {{- craft.frontMatter.source("_components/link") -}} </pre>
如果您在模板中使用简单的字符串和数组作为输入变量,甚至可以通过将它们传递回模板的正常{% include %}
来嵌入一些输出示例
{% if component.examples is defined %} <h3>Examples</h3> {% for example in component.examples %} {# Output the rendered template with the example data #} {% include "_components/link" with example only %} {# Output the escaped rendered HTML output#} <pre>{% filter escape('html') %}{% include "_components/link" with example only %}{% endfilter %}</pre> {% endfor %} {% endif %}