Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Create a slug system with Strapi v4
Oscar Bustos
Oscar Bustos

Posted on

     

Create a slug system with Strapi v4

Let's create a slug system with Strapi V4.

1 Create a new file following this structure

./src/api/[api-name]/content-types/[content]/lifecycles.js
Enter fullscreen modeExit fullscreen mode

We can control the lifecycle on this file, so we can transform our information on several events. Check the documentation.

2 Install slugify dependency

yarn add slugify
Enter fullscreen modeExit fullscreen mode

3 Add code on your lifecycle file.

const slugify = require("slugify");module.exports = {  beforeCreate(event) {    const { data } = event.params;    if (data.title) {      data.slug = slugify(data.title, { lower: true });    }  },  beforeUpdate(event) {    const { data } = event.params;    if (data.title) {      data.slug = slugify(data.title, { lower: true });    }  },};
Enter fullscreen modeExit fullscreen mode

As you can see the slug is based on our title.

That's it!

So easy

Top comments(3)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
kunal2001 profile image
Hanuman2001
  • Joined

Thanks very much it really helped

CollapseExpand
 
jackjones profile image
Jack Jones
Self-taught hobbyist web developer, hoping to eventually build a career.
  • Location
    Lincolnshire, United Kingdom
  • Joined

This is now a feature natively built into Strapi V4.

Essentially you can create a second 'ID' field that takes the title and converts it into a slug automatically :)

CollapseExpand
 
olyphotographer profile image
Peter Arnold
  • Work
    Developer at Siemens
  • Joined

This was really helpful! Thanks

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

👧🏻👧🏻 Okayest dad👨🏻‍💻👷🏻‍♂️ Frontend Developer🏋️‍♂️🏃‍♂️‍➡️ Facing my best version⬇️ Personal projects ⬇️🤖 generaterobotstxt.com🍿 topdelmes.com
  • Location
    ⛰ Ciñera Valley
  • Work
    Frontend Developer
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp