19

I would like to automatically insert a last updated timestamp (Not the date variable for the page) for each post at Jekyll build time, how to achieve that? I think I have to declare a variable but I am not sure how to assign the value to that variable.

For example, some time I update an old post, beside showing the post date, I also want to show the last update date.

I have tried {{Time.now}} but seems does not work.

XY L
  • 25,431
  • 14
  • 84
  • 143

1 Answers1

24

The only collection that has a modified_time is site.static_files. Not so useful in our case.

One way to get the last-modified-date for posts in your Jekyll site is to use a hook (documentation).

_plugins/hook-add-last-modified-date.rb

Jekyll::Hooks.register :posts, :pre_render do |post|

  # get the current post last modified time
  modification_time = File.mtime( post.path )

  # inject modification_time in post's datas.
  post.data['last-modified-date'] = modification_time

end

It's now available in your posts as : {{ page.last-modified-date }}. And you can format this date with the a date filter like {{ page.last-modified-date | date: '%B %d, %Y' }}. See the Alan W. Smith excellent article on date Jekill Liquid date formating topic.

Important notice : hooks are not working on Github pages.

David Jacquel
  • 51,670
  • 6
  • 121
  • 147
  • I will try the plugin and thanks for the reminder (I will build the page before pushing to `gh-pages`). – XY L Apr 22 '16 at 01:15
  • An approach that does not require hooks is to save all your modification dates to ./_data/mtimes.json and then read that file from Jekyll. – William Entriken Mar 21 '20 at 21:13
  • Does the approach above work for Pages as well, instead of Posts? – O0123 Dec 22 '20 at 11:13
  • @O0123 yes just change `:posts` to `:pages` on first line. You will then have à `page.last-modified-date` on any page. – David Jacquel Dec 22 '20 at 15:21