Basic Data and Templating Using Liquid

Liquid is one of the template languages that Eleventy can process. We will try that by adding some data into the index.html file, using what is called front matter. The syntax is based on YAML (a type of markup language).

Edit your index.html by adding two lines of --- with some data in between, as seen below. This is called front matter. We are creating one variable title, with a value of Eleventy Title from Data. The front matter has to be at the top of the page above the HTML, otherwise it will be displayed like any other text.

What we are also changing is the text inside the title and <h1> tags. We're replacing both with {{ title }}. The double curly brackets indicate where Eleventy is to automatically insert a value into the HTML, in this case, title's value from the front matter. This particular syntax is from the Liquid template language.

---
title: Birds
---
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ title }}</h1>
</body>
</html>
			

Now check the page in your browser. The title and the header should now match the value from the front matter.

Now let's try cycling thru a list of data (sometimes called an array).

Edit your index.html by adding some more values to the front matter, and some more tags in the HTML. The new values are included in a list named birds. Note that indenting in front matter must be done with spaces, not tabs.

The new tags provide commands, so instead of the {{ }} form, they use a {% %} form. In this case, a for loop is created with an opening tag and a closing tag. It cycles through the birds list, creating a discrete variable bird each time, that can then be inserted in the HTML.

---
title: Birds
birds:
  - robin
  - finch
  - sparrow
---
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ title }}</h1>

    <ul>
        {% for bird in birds %}
        <li>{{ bird }}</li>
        {% endfor %}
    </ul>

</body>
</html>
			

Check the page in your browser. A list should now additionally appear on the page. And if you open _site/index.html in your editor, you should see:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Birds</title>
</head>
<body>
<h1>Eleventy Title from Data</h1>
<ul>

	<li>robin</li>

	<li>finch</li>

	<li>sparrow</li>

</ul>
</body>
</html>
			

Whitespace (Line Breaks)

There will be line breaks around the lines with the <LI> tags. To clean this up, adding dashes to the loop tags prevents adding line breaks.

<ul>
    {%- for bird in birds -%}
    <li>{{ bird }}</li>
    {%- endfor -%}
</ul>
			

With the dashes at the start and end of the tags, the <LI>s will end up all on one line. To keep each <LI> on it's own line, just add dashes at the end of the tags.