← Writing

Deploying Eleventy and Tailwind CSS to Netlify - Part 2

Taking your simple site and turning it into a working blog.

Creating a Collection

In Eleventy, a collection is a group of related content, such as blog posts or product pages. The tutorial assumes you already created a folder for blog posts at src/site/blog.

To define collection parameters, create a JSON file at src/site/blog/blog.json:

{"layout" : "post","tags" : "post","templateEngineOverride": "njk,md"}

This establishes a post class, meaning any file in this directory will use the post layout and receive a post tag.

Create a corresponding post layout in src/site/_includes/layouts/post.njk:

---
layout: base
pageClass: post
templateEngineOverride: njk, md
---
<header>
<h1 class="title">{{ title }}</h1>
<h2 class="subtitle">{{ subtitle }}</h2>
</header>
{{ content | safe }}

Add a layout alias in .eleventy.js after the existing base layout alias:

eleventyConfig.addLayoutAlias('base', 'layouts/base.njk');

Now any markdown file in the blog directory creates a corresponding page. Create an example blog post at src/site/blog/my-first-post.md:

---
title: My first blog post!
subtitle: Trying some stuff out in Eleventy.
date: 2021-01-09
---
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lobortis scelerisque fermentum dui faucibus in. Velit dignissim sodales ut eu. Non consectetur a erat nam at lectus. Lacus luctus accumsan tortor posuere ac ut.

Morbi tristique senectus et netus. Phasellus faucibus scelerisque eleifend donec pretium vulputate sapien. Nunc vel risus commodo viverra maecenas accumsan lacus. Fringilla urna porttitor rhoncus dolor purus non enim praesent. Aenean vel elit scelerisque mauris pellentesque pulvinar pellentesque. Ut sem nulla pharetra diam sit. Et malesuada fames ac turpis egestas integer.

Non tellus orci ac auctor augue mauris augue neque gravida. Mi ipsum faucibus vitae aliquet nec ullamcorper sit amet risus.

The special header section contains metadata about the post that will be used in templates (inserted as {{ title }} and {{ subtitle }}). Write your post using standard markdown.

Run npm run watch and navigate to http://localhost:8182/blog/my-first-post/ in your browser to see the rendered post.

Creating an Index

Add a loop in your src/site/index.md file that iterates through every item in your post collection:

{% for item in collections.post | reverse %}
<article>
<time value="{{ item.date }}">{{ item.date }}</time> - <a href="{{ item.url }}">{{ item.data.title }}</a>
</article>
{% endfor %}

Now when you visit your index page, all posts will appear listed in chronological order.

A Part 2 branch on GitHub contains the code for simple-eleventy at this state. Updates with an improved template and simple addons like RSS are coming soon to create a working blog framework.

Last edited January 10, 2021