One thing that I often forget to do when editing web content is to update the front matter property lastmod
Typically, I should update this property to be YYYY-MM-DD for current date.
Well, I often forget…
So I was thinking, is there a way to programmatically set this property to the date that the file was last edited?
If not by jekyll, maybe it would be possible to set it using a perl script at a little bit of regex… Problem with that approach is that then I would set it for all files and they would now be updated to today. So next time I run it, I would set all files to today…
I use the plugin last_modified. Its filename is jekyll-file-last-modified.rb, the file sits in the _plugins folder and thus does not need to be mentioned in _config.yml, it’s automatically available. Here’s the code:
# 2020-01-10 dealt with error when file does not exist
# 2019-01-18 added, and used in footer
# modified from (thank you!):
# https://github.com/michaelx/jekyll-last-modified
module Jekyll
class LastModifiedTag < Liquid::Tag
def initialize(tag_name, path, tokens)
super
@path = path # copy into class property
end
def render(context)
# Pipe parameter through Liquid to make additional replacements possible
url = Liquid::Template.parse(@path).render context
# Adds the site source, so that it also works with a custom one
site_source = context.registers[:site].config['source']
file_path = site_source + '/' + url
# ensure it works even if the file does not exist (yet), for tags
begin
File.mtime(file_path.strip!) # last modified date
rescue
"" # if exception, return empty string
end
end
end
end
Liquid::Template.register_tag('last_modified', Jekyll::LastModifiedTag)
To use this tag (in my footer include) I capture the file’s modification date like so:
I see that you use it to get modification date in the actual content of the file. However, I need the lastmod date in the preample/front matter. Is this possible at all?
This is the plugin I use for my site, and it works fine. One caveat is that you have to fetch the entire Git history in a build pipeline, or else the plugin falls back to mtime, which is often much more recent than actual changes to the file.
For example, when deploying with GitHub Actions, you’d need
I am not sure I understand - how does this plugin set the lastmod time in the front matter? page.last_modified_at is a variable you use in your content, right? Can I access this in front matter?