Fat Buddha Designs

Affordable, Creative, Hand-Crafted Websites

Useful Eleventy Snippets

Useful Eleventy Snippets

Published:

Reading Time: (approx) 4 min

Tags that this post has been filed under.

The main content about Useful Eleventy Snippets

These are some of the Eleventy(11ty) snippets that I have found useful when developing websites.

Hiding before and after a date

These first two snippets which I have added to the same code block enable the hiding of events that have past and the hiding of posts that you only want to release after a certain date. But these can both be applied to any collection.

.eleventy.config.js

const hidePastItems = (post) => {
  let now = new Date().getTime();
  if (now > post.date.getTime()) return false;
  return true;
}
const hideFutureItems = (post) => {
  let now = new Date().getTime();
  if (now < post.date.getTime()) return false;
  return true;
}

module.exports = function (config) {

  // Returns a collection of blogposts, hiding them until after a certain date
  config.addCollection("releasedPosts", function (collectionApi) {
    return collectionApi.getFilteredByGlob('./src/content/posts/*.md').reverse().filter(hideFutureItems)
  });

  // Returns a collection of events, hiding those past a certain date, usually the date of the event
  config.addCollection("events", function (collectionApi) {
    return collectionApi.getFilteredByGlob('./src/content/events/*.md').filter(hidePastItems)
  });

}

This is my current navigation.njk partial used in conjunction with a navigation.json file in my _data directory.

navigation.njk

{% set currentUrl = page.url %}
{% if navigation.firstnav %}
<section class="navigation">
	<div class="nav-container">
		<nav aria-label="Primary Navigation">
			<div class="nav-mobile"><a id="nav-toggle" href="#!"><span></span></a></div>
			<ul class="nav-list">
      {% for item in navigation.firstnav %}
        {% set externalAttribute = '' %}
        {% set currentAttribute = '' %}
        {% if item.external %}
          {% set externalAttribute = ' rel="external"' %}
        {% endif %}
        {% if page.url == item.url %}
          {% set currentAttribute = ' aria-current="page"' %}
        {% endif %}
        <li><a aria-label="{{ item.aria }}" href="{{ item.url }}" {{ externalAttribute | safe }} {{ currentAttribute | safe }}>{{ item.text }}</a></li>
      {% endfor %}
			</ul>
		</nav>
	</div>
</section>
{% endif %}

navigation.json

{
  "firstnav": [
    {
      "text": "Home",
      "url": "/",
      "aria": "Welcome to our homepage",
      "external": false
    },
    {
      "text": "About",
      "url": "/about/",
      "aria": "Learn a little bit about us",
      "external": false
    },
    {
      "text": "Products",
      "url": "/products/",
      "aria": "Browse our lovely products",
      "external": false
    },
    {
      "text": "Events",
      "url": "/events/",
      "aria": "Some events we will be attending",
      "external": false
    },
    {
      "text": "Contact Us",
      "url": "/contact-us/",
      "aria": "Contact us today",
      "external": false
    }
  ],
  "secondnav": [
    {
      "text": "Policies",
      "url": "/policies/",
      "aria": "Our cookie and privacy policies",
      "external": false
    },
    {
      "text": "Sitemap",
      "url": "/sitemap/",
      "aria": "Find all the pages on our website",
      "external": false
    },
    {
      "text": "Terms Of Use",
      "url": "/terms-of-use/",
      "aria": "What we expect of you",
      "external": false
    }
  ]
}

You can style the [aria-current=“page”] element for a current page link.
This also means I can use the ‘secondnav’ for another navigation element say in the footer using the same navigation.njk but swapping out the ‘firstnav’ for ‘secondnav’.

Eleventy Filters

Filters in Eleventy are a nice way of keeping code ‘dry’ or ‘clean’ and can be powerful.

I like to keep my .eleventy.config.js as clean as possible, so I keep my filters in a file called filters.js which is in the root and then under config/utils.

I then call and implement my filters in the .eleventy.config.js like this :-

const filters = require('./config/utils/filters.js');

module.exports = function (eleventyConfig) {

  // 	------------------- Filters -----------------------
  Object.keys(filters).forEach((filterName) => {
    eleventyConfig.addFilter(filterName, filters[filterName])
  });

};

Some of my more useful filters are these (for the date filters you will need to install Luxon) :-

filters.js

const {DateTime} = require('luxon');

const nth = function (d) {
  if (d > 3 && d < 21) {
    return 'th';
  }
  switch (d % 10) {
    case 1:
      return 'st';
    case 2:
      return 'nd';
    case 3:
      return 'rd';
    default:
      return 'th';
  }
};

const month_names = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
];

module.exports = {

// 	------------- Date To Format -------------------
  dateToFormat: date => {
    date = parse(date);
    return DateTime.fromJSDate(date, {
      zone: 'GMT'
    }).setLocale('en').toLocaleString(DateTime.DATE_MED);
  },

// 	------------- Date To ISO Format -----------------
  dateToISO: date => {
    date = parse(date);
    return DateTime.fromJSDate(date, {
      zone: 'GMT'
    }).setLocale('en').toISODate({
      includeOffset: false,
      suppressMilliseconds: true
    });
  },

// 	------------- Feed.xml Date -------------------
  dateFeed: date => {
    date = parse(date);
    return DateTime.fromJSDate(date, {
      zone: 'GMT'
    }).setLocale('en').toHTTP();
  },

// 	------------- Long Readable Format -------------------
  longDate: date => {
    date = parse(date);
    let day = date.getDate();
    return `${day}${nth(day)} ${month_names[date.getMonth()]}, ${date.getFullYear()}`;
  },

// 	------------- Day -------------------
  day: date => {
    return parse(date).getDate();
  },

// 	------------- Day With Ordinal -------------------
  dayOrdinal: date => {
    let day = parse(date).getDate();
    return day + nth(day);
  },

// 	------------- Month -------------------
  month: date => {
    return parse(date).getMonth() + 1;
  },

// 	------------- Month By Name -------------------
  monthName: date => {
    return month_names[parse(date).getMonth()];
  },

// 	------------- Year -------------------
  year: date => {
    return parse(date).getFullYear();
  },

// 	------------- Sort By Title -------------------
  sortByTitle: arr => {
    arr.sort((a, b) => (a.title > b.title ? 1 : -1));
    return arr;
  },

// 	------------- Sort By Newest -------------------
  sortByNewest: arr => {
    arr.sort((b, a) => (a.date > b.date ? 1 : -1));
    return arr;
  },

// 	----------- Limit Items In An Array -----------------
  limit: (array, limit) => {
    return array.slice(0, limit);
  },

// 	------------- Strip Quotation Marks -------------------
  stripmarks: function (value) {
    value = lodash.replace(value, /\"$/, ' ');
    return value;
  },

// 	--------- Add 2 Decimal Places To An Integer -----------
  addDecimals: function (value) {
    value = (value / 1).toFixed(2);
    return value;
  },

// 	------------- Capitalise A String ---------------
  capitalize: function (str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  },

// 	----------- Change A String To Lowercase-------------
  lowercase: function (value) {
    value = lodash.deburr(value).toLowerCase();
    return value;
  },

// 	----------- Change A String To Uppercase-------------
  uppercase: function (value) {
    value = lodash.deburr(value).toUpperCase();
    return value;
  },
};

Eleventy has some URL filters built in, which yu can find here, another great source of filters, (and code in general) is 11ty Rocks.

As I find/develop useful snippets they will be added here, I hope these may be of some use to you.

Journal Index

Previous Article: Should you employ a website developer?

Next Article: Developing Websites With Eleventy