Search code examples
jekyllliquid

How to set a default date on a Jekyll site?


I want the date values of all pages to default to site.time if no date is provided in the filename or front matter. Using {{ site.time }} in an html file (such as a layout) works but when I set it either in the front matter of the document, or in the defaults I get this error:

Invalid date 'site.time': An invalid date format was found in a front-matter default set: {"scope"=>{"path"=>""}, "values"=>{"date"=>"site.time"}} (Jekyll::Errors::InvalidDateError)

Here's my code in _config.yml:

defaults:
  - scope:
      path: ""
    values:
      date: "{{ site.time }}"
      # OR
      date: site.time
      # OR
      date: "{{ site.time | date: '%d %b %Y' }}"
      # OR
      date: "now"
      # OR
      date: "{{ 'now' }}"

Is this possible? If so, what am I doing wrong?

Edit: I could do something like this:

{% if page.date %}
<div>Document date: {{ page.date }}</div>
{% else %}
<div>Document date: {{ site.time }}</div>
{% endif %}

But I'd have to do this for every single time and I'd rather just use page.date with the defaults as designed.


Solution

  • _config.yml file is a static configuration file, you can't (easily) put the code that will be evaluated there.

    The most viable approach is having a check if the variable is there and fallback to default one. You can use shorter form with liquid default filter:

    <div>Document date: {{ page.publication_date | default: site.time }}</div>
    

    Also, I'd recommend avoiding variable name date as it's already defined by Jekyll and used to generate url path for posts.