Select only 3 children from a page

Hello,
I am trying to display 3 children on a page “news” at the homepage.

I have successfully displayed them with

{% for e in 0..2 %}
  {{ currentPage.children.nth(e).content }}
{% endfor %}

Unfortunately, I want to display them ordered by date (.order(“date”, “desc”)) but it won’t work together.

How can I do {{ currentPage.children.order(“date”, “desc”).nth(e).content }}?

Or is there another possibility to display it via some function?

(For example this but still not working)

{% for p in currentPage.children.order("date", "desc").maxCount(3) %}
  {{ p.content }}
{% endfor %}

Full code with macro which is getting parameter of the page (page)


{% for p in page.children.order("date", "desc").maxCount(3) %}
  <div class="col-md-3">
    <div class="newBcg">
      <div class="img">
        <a href="{{ p.url }}">
          {% if p.media.images is not empty %}
            {% set img = p.media.images|first.url %}
            <img src="{{ img }}" class="img-fluid" />
          {% else %}
            <img src="{{ tUrl }}/images/news.jpg" class="img-fluid" />
          {% endif %}
        </a>
      </div>
      <div class="col-md-12">
        <a href="{{ p.url }}"><h4>{{ p.title }}</h4></a>
          <p>{{ p.content }}</p>
          <p class="date">{{ p.date|date("d.m.y") }}</p>
         <a href="{{ p.url }}" class="float-right more">Více</a>
       </div>
     </div>
   </div>
 {% endif %}
{% endfor %}

Thank you in advance for your replies,
Junek

Perhaps like this:

{% set first_three_children = currentPage.children.order("date", "desc") %}
{% for e in 0..2 %}
  {{ first_three_children.nth(e).content }}
{% endfor %}

I must say, I haven’t tested it.

1 Like

@Junek According the docs on Grav’s API

page.children():

The following should solve your issue:

{% for p in currentPage.children.order("date", "desc").slice(0, 3) %}
  {{ p.content }}
{% endfor %}
1 Like

Well, it’s working but let’s say we have 1 tousand posts. It’s brings too much data into variable.

Anyway it works!

Thank you for your reply!

Yess, that’s exactly what I’m looking for!

Big thanks!