Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active October 18, 2023 18:23
Show Gist options
  • Select an option

  • Save morgyface/384ce16389a6a76f8dda7c0a8e5dbbe4 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/384ce16389a6a76f8dda7c0a8e5dbbe4 to your computer and use it in GitHub Desktop.
Eleventy nunjucks useful stuff
{% if not page.fileSlug|length %}
This is the home page<br>
We know this as the homepage has no slug<br>
So when we use a filter to get the length of the page slug it returns false if we are on the homepage<br>
So if we preceed that test with an if not conditional we know we are on the homepage<br>
We are essentially saying if the page slug is empty do something.
Also see it used in a ternary style arrangment below.
{% endif %}
{{ title if page.fileSlug|length else heading }}
Use 11ty provided data to create a slug and title
{% set slug = page.fileSlug %}
{% if not slug|length %}
{% set title = "Home" %}
{% else %}
{% set title = slug|capitalize %}
{% endif %}
Create an empty array
{% set featured = [] %}
Get the number of items in an array
{% collections.posts | length %}
Get first or last items in an array
{% set firstPost = collections.posts | first %}
{% set lastPost = collections.posts | last %}
Use the 11ty universal filters to fetch the previous and next items in a collection
{% set previousPost = collections.posts | getPreviousCollectionItem(page) %}
{% set nextPost = collections.posts | getNextCollectionItem(page) %}
Push posts into an array
{% set featured = (featured.push(previousPost), featured) %}
{% set featured = (featured.push(nextPost), featured) %}
Check to see if an array is not empty
{% if featured | length %}
{# Do stuff #}
{% endif %}
Show only the first n items from an array
{%- for item in collections.posts.slice(0, 2) -%}
{# item #}
{%- endfor -%}
OTHER ELEVENTY PROVIDED DATA VARIABLES
{{ page.templateContent }}
{{ page.template }}
{{ page.url }} URL can be used in <a href> to link to other templates
{{ page.fileSlug }} For permalinks: inputPath filename minus template file extension
{{ page.filePathStem }} For permalinks: inputPath minus template file extension
{{ page.date }} JS Date Object for current page (used to sort collections)
{{ page.inputPath }} The path to the original source file for the template. Note: this will include your input directory path!
{{ page.outputPath }} Depends on your output directory (the default is _site)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment