19
votes
Accepted
How do you filter matrix blocks by type?
You can grab a specific block type in Matrix by doing this:
{% for block in entry.myMatrixField.type('typeOne') %}
{{ block.text | markdown }}
{% endfor %}
If you wanted to know the number of ...
18
votes
Remove the last comma in an inline list of tags?
There's a couple of special variables available while for looping through an array. In your case I'd make use of loop.last.
{{ tag }}{{ not loop.last ? ', ' }}
This is the expression using the ...
15
votes
Is it possible to break out of a loop in twig?
Currently there is no special build-in command to do it (unless you want to use a plugin, as stated by Brandon Kelly). There is a workaround, however. The workaround is to check for additional ...
15
votes
Accepted
Advanced query/filter based on date and values
You're actually closer than you might think. All you need to do is add your field handles as parameters. I prefer to use the hash style of declaring parameters but either way will work, I just find ...
14
votes
Accepted
How do I loop through entries for a specific entry type?
{% set entries = craft.entries.section('pages').type('blogPost') %}
{% for entry in entries %}
{{ entry.title }}
{% endfor %}
Is what I have cobbled together... any pointers on improvements would ...
13
votes
Accepted
How do you return a message if no entries are found?
The for tag has an else clause by which you can render a replacement block if no iteration took place because the sequence was empty.
<ul>
{% for user in users %}
<li>{{ user....
13
votes
Accepted
Total sum within loop
To do math in twig, you will need to use the set tag to do assignments, and the + operator to do addition. When doing math inside a for loop, you will need to keep in mind that
loops are scoped in ...
11
votes
Accepted
How do I set a variable in Twig if a value exists more than once in a loop?
This can be accomplished by creating an array of the entry years. Inside the loop that's building the array, a conditional checks if the year already exists in the array... if the year exists, a ...
11
votes
Accepted
Display entries if Field Date is past Now
You can combine a for and if statement in twig, so you don't necessarily need to use search.
Something like this might get you a bit closer:
{% for entry in craft.entries.section('event') if entry....
10
votes
Accepted
Group looped entries into blocks and wrap in markup every x number of loops
The array slice something you are looking for is Twig's batch filter. Here's how you'd set up the groups and use loop.index to generate the class name.
{# Use the `find()` method to return an array ...
10
votes
Accepted
Remove the last comma in an inline list of tags?
An alternative, if you are getting the tags from the Tag Field type, is the Join filter:
{% if post.tags | length %}
Tags: {{ post.tags | join(', ') }}
{% endif %}
10
votes
Accepted
How to correctly output a Table Field?
I suppose in your example codePoints is the actual Table field.
In order to output the table rows, the template should look like this:
{% if block.codePoints | length %}
<ul>
{% for ...
10
votes
Accepted
How to create new variable from For Loop results
If I understood your question correctly then you should be able to do it as follows:
{% set sizes = [] %}
{% for productAttribute in entry.productAttributes %}
{% set sizes = sizes|merge([...
8
votes
Accepted
Is it possible to break out of a loop in twig?
Marion Newlevant wrote a Craft plugin that adds {% break %} and {% continue %} tags to Twig:
https://github.com/marionnewlevant/craft-mnbreakandcontinue
The Craft 3 version is Twig Perversion
8
votes
Accepted
Fetch Single asset without for loop?
You can call the first() function to just get the first image:
{% set image = block.backgroundImage.first() %}
{{ image.getUrl() }}
But this will fail if there is no image. So to be safe, you need:
...
8
votes
Accepted
Use loop index number in a Twig variable
I found the answer in the Twig documentation:
http://twig.sensiolabs.org/doc/templates.html#variables
You can use a dot (.) to access attributes of a variable (methods or properties of a PHP object,...
8
votes
twig for loop put every 2 elements in a new container
I usually do this like so:
{% for block in blocks %}
{% if loop.index0 % 2 == 0 %}
<div>
{% endif %}
{# other stuff #}
{% if loop.index0 % 2 == 1 or loop.last %}
</div>
...
7
votes
Add ordinal suffix to loop.index
This can also be done with a Twig macro, rather than creating a plugin:
{% macro ordinal(number) %}
{%- spaceless %}
{% if ((number % 100) >= 11) and ((number % 100) <= 13) %}
{{...
6
votes
Accepted
SET versus FIND
You're exactly right: The advantage of using the variable is that you can re-use it throughout your template, which helps keep things DRY.
When you use craft.entries in your template, Craft serves up ...
6
votes
Accepted
Is it possible to change a loop if mobile browser is detected?
You should close your for-tag pair within the {% if ... %}.
So:
{% if craft.request.isMobileBrowser %}
{% for batch in craft.entries.section('afval')|batch(2) %}
...
{% endfor %}
{% ...
5
votes
Accepted
Outputting Matrix Loop in Template
It looks like you're pretty close, but those field names need to be called as attributes on block:
{% for block in entry.threeHomepageImages.type('images') %}
{% if block.image|length %}
{...
5
votes
Outputting Matrix Loop in Template
You're almost there.
Every block returns a MatrixBlockModel, so you have to reference your block when getting the attributes:
{% for block in entry.threeHomepageImages.type('images') %}
<h2&...
5
votes
Remove the last comma in an inline list of tags?
If you you have a given string and can't influence how it is generated, use the slice filter to crop that last comma:
{% set tags = 'Alpirsbacher Klosterbräu, Rothaus Tannenzäpfle, Neumarkter ...
5
votes
Accepted
Why are variables persisting inside of my for loop?
This is totally normal and expected behavior. In fact, it's critical for some looping situations, and pretty standard across programming languages. Wouldn't you expect to find this same behavior in ...
5
votes
calculating average ratings from a series of review fields
Something like this should work:
{% set reviews = craft.entries.section('reviews').relatedto(entry) %}
{% set value = 0 %}
{% set condition = 0 %}
{% set reception = 0 %}
{% set count = 0 %}
{% for ...
5
votes
twig for loop put every 2 elements in a new container
I think batch that @Alec Ritson mentioned is definitely the way to go.
However, here's another approach for fun.
You can use cycle.
{{ cycle('<div>', '') }}
{{ foo }}
{{ cycle('</div>'...
5
votes
Accepted
Add ordinal suffix to loop.index
You'd want to write a plugin that added an |ordinal Twig filter.
Then from your template, you would do: loop.index|ordinal.
The logic in the plugin would look something like:
public function ...
5
votes
Accepted
Check and remove repeat entries from loop
I'd probably try to filter those out in your initial query, but if you've already got them, something like this should work:
{% set existingIds = [] %}
{% for event in events %}
{% if event.id ...
5
votes
Accepted
Is there a better way than stacked if else
There is certainly a lot of repeated code here so we can definitely improve on that! There are so many ways you could handle your Twig templates but this is how I would do it:
<div id="slider-with-...
4
votes
How to correctly output a Table Field?
Craft adds those extra elements to each array of table cells only if there's column handles defined in your Table Field.
This allows you to not only access a cell's value via row.col1, row.col2, etc. ...
Only top scored, non community-wiki answers of a minimum length are eligible
Related Tags
forloop × 129templating × 47
loop × 21
matrix × 17
entries × 15
conditional × 9
craft3 × 7
assets × 7
categories × 6
datetime × 6
variable × 6
entry × 5
field × 5
filter × 5
limit × 5
search × 4
tags × 3
javascript × 3
pagination × 3
plugin-supertable × 3
table-field × 3
group × 3
math × 3
relations × 2
cache × 2