1

I'm using this code to remove duplicate entries from my loop:

{% set existingIds = [] %}
 {% for entry in entries %}
    {% if entry.id not in existingIds %}
  <div class="column is-4">
{% include '_blocks/small/entries.twig'  %}
</div>
 {% set existingIds = existingIds|merge([entry.id]) %}
    {% endif %}
{% endfor %}

Everything working good but the problem is that if I have set to display 3 entries - I will get 2 or less if existingIds will be found. What I want to do is to replace that duplicate with the other entry to have always 3 entries to display.

4
  • Where do the entries come from? Are there more available entries to display in there? Can you simply query more items? How do you end up with duplicates in the first place?
    – MoritzLost
    Aug 10 at 5:59
  • It looks like this: pastecode.io/s/w5q2uqde So in this case I have one article duplicated and that leads that the last block (with 3 articles) display only 2 of them since one was displayed above. Aug 10 at 6:39
  • Why use three separate queries instead of just using one query to get the required number of entries?
    – MoritzLost
    Aug 10 at 6:58
  • I don't know how to display three different styling in one query Aug 10 at 7:05
1

Based on the example you linked: You can prevent duplicate entries by explicitly excluding the entries you've already seen using the id method. Since you already have an array of IDs you have already displayed (existingIds), you only need to prepend 'not' to negate the query and exclude those entries:

https://craftcms.com/docs/3.x/entries.html#id

{% set featuredArticle = craft.entries
    .section('articles')
    .id(['not']|merge(existingIds))
    .one() %}

This will ensure you always get an entry you haven't displayed before. This also allows you to get rid of the offset().


Sidenote: I'm using one() instead of all() to execute the query. This returns only a single entry instead of an array of entries, so you can remove the limit(1) call as well. It also allows you to get rid of the loop, since the result is a single entry instead of an array of entries.

2
  • Amazing! I find out how to use slice as well so now featured section looks like this: pastecode.io/s/tbmh68a0. I added id method to lower column since I don't want any of featured content to be display in it and it looks like this: pastecode.io/s/psqtax01 Is it correct way to implement everything? Aug 10 at 8:22
  • @LukasSnarskis Looks good to me! If this solved your issue, could you mark my answer as accepted? Thanks!
    – MoritzLost
    Aug 10 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.