💎 PREMIUM: Blog/eleventy today - Collection

Eleventy - today’s date as a global variable

A calendar for the month of april with a day circled is in the center of the frame. The eleventy possum is floating beside it on a balloon. It is cast againt a soft purple background.

Sometimes, you want to use today’s date in a template. Examples include a copyright notice that includes the current year, and adding a last built date to your site’s footer.

Not all templating languages provide a simple way to get the current date. For example, Nunjucks does not provide date capabilities at all! Let’s create our own year and now global variables that will work across all templating languages.

Global data files for today’s date

We can create global data variables through a global data file. You create a JavaScript file that lives in the global data folder, the folder is _data by default. You can change this through the dir.data configuration option if you want. Whatever you name the file will the name of the variable in available in templates.

The current year as a variable

So, in our case lets create a year.js data file that will return the current year as a String. Below is the code, written in ESM (Eleventy v3+ is required to use ESM):

Javascript
// _data/year.js

export default (function () {
  return new Date().getFullYear();
})();

The function needs to be written as an IIFE (Immediately Invoked Function Expression) in order to produce the year as a value when it is encountered by Eleventy. This will return the current full year as a String.

To use in a Nunjucks template, you can write the:

Nunjucks
<p>© Skynet 1998 - {{ year }}</p>

The current date as a variable

If you want a variable that returns a Date Object that you can format yourself, you do the following:

Javascript
// _data/now.js

export default (function () {
  return new Date();
})();

To use in a Nunjucks template, you can write the:

Nunjucks
<p>Last built at: {{ now }}</p>

Source code

The source code is available in this repo. You can find it as an independent project in the todays-date folder.

example of using now and year variables

Tags