I'm working on a reviews site where each entry has a series of fields, but on the front end, different pages are used depending on whether fields have values in them or not, e.g. if fieldX
has data, on the front end you can access a page at a URL like /review/entryName/fieldX
. And links to those pages appear if fieldX|length
.
But now I need to create next and prev page links. If field1
doesn't have a value, then you have to keep going through the list of possible fields that might have their own page to find one which has a value to create the next link, e.g. it might be field5
having skipped out 2, 3, 4.
What I have so far is
{% set reviewPages = {
0: {
'field': entry.field1|length,
'text': 'Field 1',
'url': 'field_1'
},
1: {
'field': entry.field2|length,
'text': 'Field 2',
'url': 'field_2'
}
}
%}
{% set prev = null %}
{% set next = reviewPages[1] %}
{% for page in reviewPages %}
{% if page.url == segment_3 %}
{% if prev is not null and (prev.field > 0) %}
<a href="{{ entry.url }}/{{ prev.url }}">{{ prev.text }}</a>
{% else %}
{% continue %}
{% endif %}
{% if next is not null and next.field > 0 %}
<a href="{{ entry.url }}/{{ next.url }}">{{ next.text }}</a>
{% else %}
{% continue %}
{% endif %}
{% endif %}
{% set prev = page %}
{% if loop.revindex <= 2 %}
{% set next = null %}
{% else %}
{% set next = reviewPages[loop.index0+2] %}
{%endif%}
{% endfor %}
This works fine if all the fields have data, but breaks down when it encounters a next field which doesn't have any.
I need something for the loop to continue on to the next item in the array and test that and so on until it finds one with data.
I thought I might be able to use https://plugins.craftcms.com/twig-perversion which provides a continue
tag but it doesn't work which is probably because the first line in the loop is checking whether the url of the loop item matches the url of the page you're on and it will only match for one item in the array.