Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Content & Markdown

Select only 3 children from a page

Solved by pamtbaau View solution

Started by Jan Plechtý 7 years ago · 4 replies · 664 views
7 years ago

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

I have successfully displayed them with

TWIG
{% 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)

TWIG
{% 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)


TWIG
{% 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

last edited 02/04/19 by Jan Plechtý
7 years ago

Perhaps like this:

TWIG
{% 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
7 years ago Solution

@Junek According the docs on Grav's API

page.children():

The following should solve your issue:

TWIG
{% for p in currentPage.children.order("date", "desc").slice(0, 3) %}
  {{ p.content }}
{% endfor %}
👍 1
7 years ago

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!

7 years ago

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

Big thanks!

Suggested topics

Topic Participants Replies Views Activity
Content & Markdown · by Jochen, 8 months ago
6 99 8 months ago
Content & Markdown · by Ton Haarmans, 1 year ago
10 186 1 year ago
Content & Markdown · by Jan L'Am, 1 year ago
4 148 1 year ago
Content & Markdown · by Leonardo, 1 year ago
3 62 1 year ago
Content & Markdown · by belthasar, 1 year ago
4 257 1 year ago