How do I create a loop for repeating dummy content using Twig to help design my site before I have data in the database?
As we design and develop websites we don't always have all of the final resources for a project available to us. In the case that you just need to output some repeating items on your page, you can use this code snippet:
{% for i in 1..5 %}
<p>{{ i }}. This text will display in your template 5 times.</p>
{% endfor %}
That code would output:
<p>1. This text will display in your template 5 times.</p>
<p>2. This text will display in your template 5 times.</p>
<p>3. This text will display in your template 5 times.</p>
<p>4. This text will display in your template 5 times.</p>
<p>5. This text will display in your template 5 times.</p>
This can be useful for building out index pages, highlight content, galleries, or any other repeating items in your designs that you wish to build out before you have the actual data. The syntax above is Twig's shorthand for the range
operator. A little more clearly, that same code could be written like so:
{% for i in range(1, 5) %}
<p>{{ i }}. This text will display in your template 5 times.</p>
{% endfor %}
If the situation calls for it, we can do the same using letters. Let's make this example a bit more advanced and use each letter to create a list links, like we might find on a directory page.
<ul>
{% for letter in 'a'..'z' %}
<li><a href="directory#{{ letter }}">{{ letter }}</a></li>
{% endfor %}
</ul>
That example will output the following code in your template:
<ul>
<li><a href="directory#a">a</a></li>
<li><a href="directory#b">b</a></li>
<li><a href="directory#c">c</a></li>
<!-- The rest of the alphabet -->
</ul>
When our database is ready and full of content, we can then go through our templates and just swap out our temporary for
loop with the range
function {% for i in 1..5 %}
and substitute in our appropriate Craft tag {% for entry in craft.entries.section('blog').limit(5) %}
and field variables.
Our dummy loop:
{% for i in 1..5 %}
<h2>Example Title</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation.</p>
{% endfor %}
Transitions nicely into our actual loop:
{% for entry in craft.entries.section('blog').limit(5) %}
<h2>{{ entry.title }}</h2>
{{ entry.body }}
{% endfor %}