字段
所有默认可用的字段列表。
Fields 定义了用于 文档 和 集合 中条目的数据类型和界面。
所有 Fields 必须有一个 name
和一个 type
。
name
: 用于在文档中存储值的变量名。type
: CMS 前端中使用的数据格式和界面。
假设我们有以下 markdown 文档:
---
title: Happy new year
date: 2024-01-01 00:00:00
---
I hope you have a **great 2024**.
这个文档有三个 Fields:
title
,这是一个纯文本。date
,这是一个日期时间。content
,这是一个 markdown 内容。
要配置 LumeCMS 来编辑此页面:
cms.document("happy-2024", "src:happy-2024.yml", [
{
name: "title",
type: "text",
},
{
name: "date",
type: "datetime",
},
{
name: "content",
type: "markdown",
},
]);
现在你可以在 CMS 中修改此文件的内容,并且每个 field 将根据 field type 拥有一个界面。
如果只需要 name 和 type,为了简洁,你可以使用 name:type
格式的字符串。例如,前面的例子可以简化为:
cms.document("happy-2024", "src:happy-2024.yml", [
"title: text",
"date: datetime",
"content: markdown",
]);
字符串表示法允许使用感叹号将 value 定义为 required:
cms.document("happy-2024", "src:happy-2024.yml", [
"title: text!", // 这个 value 是必需的
"date: datetime",
"content: markdown",
]);
常用字段
Fields 可以有其他 options 来验证或自定义某些方面。 以下 options 在所有 fields 中都可用:
- name (required)
- 用于存储 value 的变量名。
- type (required)
- field type。每个 field type 都有不同的 UI,并且可以在保存前转换 value。
- label
- 在 UI 中可见的名称。如果未定义,将使用
name
option。 - description
- 可选的描述,将在 UI 中 label 旁边可见。
- value
- 如果未定义此 field 的默认 value。它用于在集合中创建具有一些预定义 values 的新文档。
- attributes
- 包含要传递给 UI 中 input 的额外 attributes 的对象。这允许设置 HTML 验证 attributes,如
required
、min
、max
、maxlength
、pattern
等。 - init
- 在前端显示此 field 之前将调用的函数。它允许动态更改 field 配置。更多信息见下文。
这是一个包含一些额外 options 的 fields 示例:
[
{
name: "title",
type: "text",
label: "Title of the page",
description: "It will be visible in the browser tab",
attributes: {
required: true,
maxlength: 100,
},
},
{
name: "date",
type: "datetime",
label: "Created date",
value: new Date(),
description: "Set a future date if you want to publish it later",
attributes: {
placeholder: "For example: 2024-01-01 00:00:01",
},
},
{
name: "content",
type: "markdown",
label: "Page content",
value: "Write **markdown** code here",
description:
`<a target="_blank" href="https://www.markdownguide.org">More info about markdown syntax</a>`,
},
];
init
函数
init
函数允许在每次使用 field 时动态更改任何 field 的配置。 让我们看下面的例子:
{
name: "password",
type: "text",
init(field) {
field.value = generateRandomPassword();
}
}
这里我们定义了一个 text
field 来存储密码。 每次在集合或文档中使用此 field 时,都会动态生成默认 value。
init
函数的第二个参数是一个包含 CMS 内容(所有集合、文档、上传等)的对象。 此对象还包含在配置中传递的 data 变量。 由于 Lume 适配器自动将 site
实例存储在此对象中,因此可以使用 site data 修改 field 配置。 例如:
{
name: "tags",
type: "list",
init(field, { data }) {
const site = data.site;
const allTags = site.search.values("tags");
field.options = allTags;
}
}
在这个例子中,我们使用 Search.values 函数来获取网站中使用的所有 tags,并配置 field 的 可用 options。