Before we saw the for loop where we can loop over a collection of items.
Fori is a tag in liquid that is used to create lists or collections in which we are going to let the user add an indefinite amount of iterations containing input fields. That’s why the i in fori stands for input
The loop ends when the user adds the last piece of information on the list
This tag always needs to be opened and closed
The opening tag has 2 essential elements:
Key word: any word of your choice without spaces or punctuation. It will be used when defining input fields within the loop.
Collection: word “custom” followed by a dot and a collection name of your choice. We can see this as a table where we will store different elements.
It’s important to remember the way we name input fields in order to understand fori loops. For input fields we always use the word custom followed by a namespace and a key. In my fori a loop, the collection name is the equivalent to “custom.namespace” in an input field.
Then when we create the input fields inside the collection we use the “key word” from the fori loop followed by a name of our choice. In the example, “item” would replace custom.my_collection so we can see “item.name” as “custom.my_collection.name“. The key ”item“ makes each element unique for each iteration.
We can see this with an example. We can create a list of all our employees by using the fori loop. We use the key word item followed by a word of our choice to create each input inside the fori loop. The user is always going to be able to enter an additional item at the end of the loop.
The collection can be seen as our table, each iteration would be a different row and each input field a different cell in a specific column.
After creating our collection we are going to be able to access to it via a for loop. In this case we have changed the key word but it doesn’t really matter as long as you use the same one for each loop, so now if I want to print the name of the employee, rather than writing item.name I need to write employee.name
Updated over 1 year ago