Templates
As you add more pages to your website, you will soon notice that many elements are repeated across pages, like the header tags. Manually rewriting them every time you make a new page can become quite tedious - this is where templates come in.
This is done by using yet another programming language called 'templating languages'. Recall that you used the following code in an earlier course:
---
layout: default.njk
---
I am a plaintext
The '---' and the text in bwteen them is actually part of a templating language called Liquid. 11ty supports Liquid out of the box, and is thus frequenrtly used. We will use Liquid templates so we don't have to write the head, body, title, and meta tags every time we make a new page. First, read the following tutorial.
Use this tutorial to move all of your head, html, body, etc. tags in your index.html into default.njk. This means your index.html should only have the texts and images, and not contain any head or meta tags. In addition, tweak default.njk so you can specify the title (in the title tag) in index.html. In other words, the first 4 lines of index.html should look like this:
---
layout: default.njk
title: Your Title
---
Notice that in the tutorial, 'title' is defined in both mylayout.njk (the template) and content-using-layout.md(main page). In such case, the title defined in the main page will be used. If you forget to deinfe the title in the main page, the title in the template will be used. This is a recommended practice, since even if you forget to define a title, the outputted website will at least how something instead of a blank title.
Macros
Macros are commonly used when you want to repeat certain group of elements over and over. For exmaple, if you are making a directory webpage that lists the image, name, and a short bio for bunch of people, instead of writing the img, header, and p tags for every one of them, it would be easier if all you needed to write were the info for each person, and the template will generate the tags for you.
Liquid unfortunately does not support macros, so we use another templating language called Nunjucks.
First, read the Nunjucks documentation about macros here:
Now, chnage the filename of your index from index.html into index.njk. This will explicitly tell 11ty that this file contains Nunjucks code. Add a macro that can take name of a skill you have (e.g. Illustrator, Figma) and a short discription of it, and output it in the following format:
- The name of your skill is in the h3 tag
- The description is in a p tag
- The above 2 is in a div tag
Use the macro you just made to list out 3 ~ 4 skills you have. In other words, in your index.njk file, you should be able to write something like:
{{ skill('Photoshop', 'I can use Ps') }}
{{ skill('Figma', 'I can use Figma') }}
and the generated html file after running 11ty should look something like:
<div><h3>Photoshop</h3><p>I can use Ps</p></div>
<div><h3>Figma</h3><p>I can use Figma</p></div>