Up until now Item slugs — that is, the human-readable, SEO-friendly strings that univocally identifies a specific resource in a permalink — were automatically generated by our integration plugins based on the title of an Item. This strategy had an obvious and quite dangerous flaw: if the title of an already published Item changed for whatever reason, some URL in your website would change as well. Ugh.
We are happy to announce the deprecation of this technique in favour of a new type of field you can add right away to your Item types: Slugs.
How does it work?
Pretty easy. Suppose we have a "Blog post" item type. First we create a string field called "Title":
And then we add a slug field. Let's call it.. well.. "Slug". We want the slug to be generated based on the "Title" field, so we select it as "Reference field". Let's make sure we also enforce a uniqueness validation, so that we'll never have two items with the same slug:
Awesome! If we switch to the Content tab, we can see that the slug will be automatically generated while we write the title for our blog posts:
Done! In the
dato.config.rb, if you're using the Ruby gem) config file we can now get the slug just like we query for any other regular string field:
dato.blogPosts.slug // => "my-awesome-article"
dato.blog_posts.first.slug # => "my-awesome-article"
Migrating existing sites
If you want to migrate your existing site to use Slug fields, follow these simple steps:
Upgrade to the latest dato plugin with
npm update datocms-client(or
bundle update dato);
If you're using Middleman, make sure you also update the
bundle update middleman-dato);
From your terminal, run the following command:
# JS version$ ./node_modules/.bin/dato migrate-slugs --token=YOUR_SITE_READWRITE_API_TOKEN# Ruby version$ bundle exec dato migrate-slugs --token=YOUR_SITE_READWRITE_API_TOKEN
The command will handle most of the work for you:
It will search for any Item type in your space containing a title field;
It will append a new Slug field to the Item type itself, pointing to the title field as "Reference field";
It will fill in the slug field of every Item with a slugified version of the title itself. By default, the command will prefix the slug with ID of the Item itself (ie.
3243-my-article-post) but you can pass the additional flag
--skip-id-prefixto avoid that.
After the migration your static site will continue to build just fine®, but please make sure to double-check the URLs of your static site as some of them might differ from the old ones.
That's it folks!
We're sure that the introduction of explicit Slug fields will make your DatoCMS static sites more solid and reliable. We also hope to have described this change in detail.. but if you encounter any problems during the migration, don't hesitate to ask for help via our Support channels!