建立一个 slug 系统

本指南将解释如何创建一个 slug 系统的职位,文章或任何内容类型。

创建属性

要开始建造 slug 系统,你需要一个 string 字段作为 slug 的基础,在这个例子中我们将使用title

您还需要另一个 string 字段,其中包含 title 的放大值,在这种情况下,我们将使用slug

Slug fields

配置内容编辑器的布局

让我们配置 edit page 的布局,使其对内容编辑器更加友好。

  • 点击 the Article link 在左边的菜单里.
  • 然后 on the + Add New Article 按钮
  • And finally on the Configure the layout 按钮

在这里,我们将能够设置 slug 字段。

  • 点击 the slug 字段
  • 在页面底部, 编辑 占位符Generated automatically based on the title.
  • 点击 OFF for Editable field option.
  • 不要忘记保存你的更新.

:::: tabs

::: tab View before

View before

:::

::: tab View after

View after

:::

::: tab View configuration

Edit View config

:::

::::

自动创建/更新 slug 属性

为此,您必须在应用程序中安装 slugify 节点模块。

完成后,您必须更新文章内容类型的生命周期,以自动完成 slug 字段 。

Path — ./api/article/models/Article.js

:::: tabs

::: tab Mongoose

  1. const slugify = require('slugify');
  2. module.exports = {
  3. lifecycles: {
  4. beforeCreate: async data => {
  5. if (data.title) {
  6. data.slug = slugify(data.title);
  7. }
  8. },
  9. beforeUpdate: async (params, data) => {
  10. if (data.title) {
  11. data.slug = slugify(data.title);
  12. }
  13. },
  14. },
  15. };

:::

::: tab Bookshelf

  1. const slugify = require('slugify');
  2. module.exports = {
  3. /**
  4. * Triggered before user creation.
  5. */
  6. lifecycles: {
  7. async beforeCreate(data) {
  8. if (data.title) {
  9. data.slug = slugify(data.title, { lower: true });
  10. }
  11. },
  12. async beforeUpdate(params, data) {
  13. if (data.title) {
  14. data.slug = slugify(data.title, { lower: true });
  15. }
  16. },
  17. },
  18. };

:::

::::

获取文章 slug

这样你就可以用这个 slug 取你的 Articles 了。

你可以通过这个请求 GET /articles?slug=my-article-slug 找到你的文章