Custom Variables in Jekyll Permalinks
The pages for this blog are built using Jekyll but you might notice that the links for the posts are not in the traditional Jekyll format of using date-title.
Jekyll does provide you with configuration options in the spirit of having your URLs the way you want ‘em, but unfortunately it’s limited to certain built-in template variables. Being a fan of customization, I decided to make a plugin which woudl let me (and you) use custom-defined font-matter variables in the permalinks.
In fact, the plugin is so simple that I can demonstrate the code right in this blog post and explain it line-by-line
module Jekyll class PermalinkRewriter < Generator safe true priority :low def generate(site) # ignore if presets like date, pretty, ordinal, or none are being used. Detect the usage by detecting the presence of the colon (:) character in the permalink value if site.config['permalink'].include? ":" site.posts.docs.each do |item| # copy the permalink value from site config, before we start substituting all the variables in it with their values item.data['permalink'] = site.config['permalink'].dup # go through the list of all custom variables site.config['permalink_custom_vars'].each do |var| # if data isn't available, we will just remove the variable's token from permalink substitution = item.data[var].to_s or '' # and if it is available, substitute it for the value item.data['permalink'].gsub! ":" + var, substitution end end end end end end
It’s not state of the art, but it works. To use it you just have to put an extra key in your
_config.yml enumerating which variables you want substituted. For instance, if you’d like the variable
author to be present in your URL, you could try something like
# will substitute :author with the variable author in your file (also works with defaults). permalink: /:author/:slug/ # You need to have this extra permalink_custom_vars array to tell the plugin which substitutions to make permalink_custom_vars: ['author'] # Note that you don't have to include the supported variables in this list as jekyll takes care of that # For a complete list of variables jekyll supports, see: https://jekyllrb.com/docs/permalinks/#template-variables
- Check out this stackoverflow answer based on which I’ve made the plugin.
- This is the github gist where you can get the latest version of the code from. It works with Jekyll 3.4.3 as the time of this writing
- You can make your own Jekyll plugins to get hooks into the Jekyll’s build system and customize your site. Check out their official plugin guide.