14.00 Use Liquid
Table of contents
- Some sample data to begin with
- Replace static HTML with Liquid
- Calling methods
- What you’ve learned
This article tells you how to use Liquid to inject data into your HTML.
Some sample data to begin with
You’ll be able to use your own data later on. For now, you’ll use sample data we’ve provided, which is in a file called processed_books.json within the _data folder.
Replace static HTML with Liquid
In portfolio.html, replace this, which is everything between the
Save your file. Refresh your browser and see the effect.
The page is displaying new data, because of your new code. The rest of this article explains the new code you added, piece-by-piece.
Iteration is when you loop through a collection of data. Here’s an example:
Read that line aloud. It says “for book in site data processed_books”. More verbosely, it means “For each book in this site’s data store in turn, replace the contents of the
book variable with information about the next book in the list”.
Once you have iterated and got a
book variable, you can “call methods” on it and turn the results of the methods into HTML.
This next line uses two method calls to output the HTML
img tag for the book’s cover.
Question: Can you see what those methods might be?
Answer: The methods called here are
You call a method using a dot:
The dot is how you ask an object for some of its information. This is also know as “calling a method”. Here you’d say you’re “calling title on book”.
title is something that a book has. The syntax
book.title is the same as saying “Book, please tell me your title”. You can do the same for pub date, for ISBN13 – in fact, any attribute that
book knows about.
Let’s look again at the code you’ve just added.
This code turns into the following HTML for the book called “The Goddess Project”. The first line creates a link in a manner specific to the code library you’re using to generate multiple pages. The second line uses two method calls to create the
img HTML tag for the book’s cover.
Learn more later
- Much of programming is about Googling and finding out answers to problems that present themselves through your own research. So read through the Liquid documentation to learn about the
date: '%b %Y'pub date Liquid filter you’ve used and discover more about Ruby by Googling, and using the resources listed earlier.
What you’ve learned
- Variables can represent complex data, and more than one instance of an object.
formethod lets you iterate through each instance of an item in a collection.
- In Ruby, a dot means ‘call a method on an object’.
- Read the docs!
- All programmers rely on Google.
- Programming is less about maths, and more about words and logic.