Automate Slug Generation in Directus Using Flows
2 minutes read time · 316 words · Tutorial
2 minutes read time · 316 words · Tutorial
In this tutorial, I'll show you how to automatically create a slug from a title using Directus Flows. We’ll automate this action within the Flow. For this example we will be building a blog collection.
Start by creating a new collection for your blogs via the Data Model. Name it "blogs". You don’t need to add optional fields, but make sure to create two fields: one called "title" and another called "slug".
Now, you have everything set up for a basic start.
When creating a Flow, give it a name, for example; "Blog Title to Slug," and add an icon if you like.
items.create
and items.update
).You should now see a checkmark icon and a plus icon on the right. Click the plus to add a new operation.
Name the operation slugify_me
and rename the key to the same. We will be using this later.
Now, select "Run Script" and delete the default content. Add this script:
module.exports = async function (data) {
// Index data to get the string you want to slugify
const text = data.$trigger.payload.title;
const slug = text
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '') // Remove unwanted characters
.replace(/[\s_-]+/g, '-') // Replace spaces/underscores with hyphens
.replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
return slug;
};
To test if this works, create a new operation on the both +
and -
and select "Log to Console." Add these logs:
Succes {{$last}}, {{$trigger}} {{slugify_me.id}} - {{operation_key}}
Error {{$last}}, {{$trigger}}
Next, create an operation to update the slug. Here’s how:
{ }
and select the current collection used in the trigger ({{$trigger.collection}}
).{
"slug": "{{ slugify_me }}"
}
To specify the correct colection item being updated, add this filter:
{
"filter": {
"id": {
"_eq": "{{ $trigger.keys[0] }}"
}
}
}
Finally, add another "Log to Console" operation to verify success. You can name it Success or anything you would like.
That’s it! You’ve created an automated slug generator using Directus Flows. If you found this tutorial helpful, please upvote it to help others find it.