Relations

为页面创建自动关联

配置参数

extensions string[]

The list of extensions this plugin applies to

Default:
[ ".html" ]
idKey string

The field name used to save the page id

Default:
"id"
typeKey string

The field name used to save the page type

Default:
"type"
foreignKeys record

The foreign keys per type (type => foreign_key)

描述

如果你有不同类型的页面,它们之间存在关联,这个插件就非常有用。例如,假设你有一些文章页面和作者页面。这个插件可以自动关联文章页面和作者页面。

安装

在你的 _config.ts 文件中导入此插件以使用它:

import lume from "lume/mod.ts";
import relations from "lume/plugins/relations.ts";

const site = lume();

site.use(relations(/* 选项 */)); // Options

export default site;

用法

这个插件需要指定页面类型以及用于建立关联的外键。例如:

import lume from "lume/mod.ts";
import relations from "lume/plugins/relations.ts";

const site = lume();

site.use(relations({
  foreignKeys: {
    article: "article_id",
    author: "author_id",
  },
}));

export default site;

在下面的例子中,我们有一些 type: articletype: author 的页面。article 类型的页面包含了与作者的关联,使用了外键 author_id:

---
id: 1
type: article
author_id: 2
---

文章 1 的内容,作者是 Laura
---
id: 2
type: article
author_id: 2
---

文章 2 的内容,作者是 Laura
---
id: 3
type: article
author_id: 1
---

文章 3 的内容,作者是 Óscar
---
id: 1
type: author
title: Óscar Otero
---

Óscar 的个人简介
---
id: 2
type: author
title: Laura Rubio
---

Laura 的个人简介

这个插件会自动为每篇文章创建 author 变量,其中包含作者的数据 (1:n 关系)。要渲染一篇包含作者信息的文章,可以这样做:

<article>
  {{ content }}

  <footer>作者:{{ author.title }}</footer>
</article>

该插件还会创建反向关联 (n:1 关系),并创建 article 变量,这是一个包含与每个作者相关联的所有文章的数组:

<article>
  {{ content }}

  <h2>创作的文章:</h2>

  <ul>
  {{ for item of article }}
    <li>
      <a href="{{ item.url }}">
        {{ item.title }}
      </a>
    </li>
  {{ /for }}
  </ul>
</article>

多重关联

你可以从同一个页面关联多个页面 (n:n 关系),方法是在外键中使用数组。例如,一篇由多位作者撰写的文章:

---
title: 这是标题
type: article
id: 1
author_id: [1, 2]
---

文章内容

自定义 id 和 type 键

默认情况下,页面通过 typeid 键的值来识别。你可以在配置中全局更改它:

site.use(relations({
  typeKey: "kind",
  idKey: "slug",
  foreignKeys: {
    article: "article_id",
    author: "author_id",
  },
}));

配置单个关联

你可以使用对象来配置单个关联。可用的选项有:

  • foreignKey (必需): 用于设置关联的键名 (例如 article_id)。
  • relationKey: 用于存储关联的键名 (例如 article)。
  • pluralRelationKey: 用于存储多重关联的键名 (例如 articles 而不是 article)。
  • idKey: 用于识别实体的键名 (默认为 id)。
  • filter: 用于过滤相关元素的自定义函数。当与 多语言插件 结合使用时非常有用,可以仅关联不仅具有相同 id 而且还具有相同语言的元素。

让我们看一个例子:

site.use(relations({
  foreignKeys: {
    article: "article_id",
    author: {
      foreignKey: "author_id",
      relationKey: "author",
      pluralRelationKey: "authors"
      idKey: "name",
    },
  },
}));

在这个例子中,author 类型的页面具有自定义配置:

  • 外键是 author_id
  • 关联键是 author。例如,与文章关联的作者存储在 author 键中。
  • 复数关联键是 authors。如果一篇文章有多个作者,他们将存储在 authors 键中。
  • id 键是 name 而不是 id