1

I'm trying to limit the amount of entries on my page.

Currently I want 1 news entry (based on if the checkbox is ticked, there could be 10 entries with the checkbox ticked but I only want to show 1 (the latest)) The issue is that the limit() twig function doesn't work with my elementCriteriaModel.

My code:

{# Checking if any news entries have the FeaturedEntry field completed #}
{% for entry in craft.entries.section('news').level(2) %}

    {% if entry.featured.contains('isFeatured') %}

        {% set news = craft.entries.section('news') %}

            <div class="insight orange">
                <a href="{{ entry.url }}">
                    <h4>News *Chosen*</h4>
                    <h3>{{ entry.title }}</h3>
                    <div class="details">
                        <span class="author">{{entry.author}}</span>
                    </div>
                </a>
            </div>

    {% else %}
            Do Something Else Here

If I attach the limit function to {% for entry in craft.entries.section('news').level(2).limit(1) %}, this only limits the amount of entries my selector can check for the featured field. If i put limit(1) it only checks the first news entry for the field.

I know i can use the slice function but I'm having some trouble inserting it into the right place.

Any help would be very appreciated.

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
Davabo
  • 67
  • 6

2 Answers2

1

What you probably want is to order them by date and than select the first.

{% set news = craft.entries.section('news').order('postDate desc').first() %}

And if you want to use limit somewhere (but I don't think this is what you are trying to get here) you should add limit(1) to this {% set news = craft.entries.section('news').limit(1) %}

Tom De Smet
  • 1,456
  • 8
  • 28
1

I was able to limit my entries by using the loop.index function

Code below:

{% for entry in craft.entries.section('insight')  %}

        {# Limit output to the first 2 #}   
        {% if loop.index <= 2 %}  

            <div class="insight">
                <a href="{{ entry.url }}">
                    <h4>Global Insights *latest random insight* </h4>
                    <h3>{{ entry.title }}</h3>
                    <div class="details">
                        <span class="author">{{entry.writer}}</span>
                    </div>
                </a>
            </div>

        {% endif %}

    {% endfor %}
Davabo
  • 67
  • 6
  • Great for you! But honestly I do not see why the normal limit wouldn't work here... In my opinion that would still be the cleanest and fastest solution. – Tom De Smet Feb 09 '17 at 07:08
  • Its because of the elemental criteria model apparently, using limit was limiting how many entries my code was checking instead of how many it outputs, for example limit(3) was only running the code through the first 3 entries in that section. Weird but i found a work around. Thanks for your help tho! – Davabo Feb 09 '17 at 10:27