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

Is the method ofType usable in a collection defined with twig syntax?

Started by Muut Archive 10 years ago · 4 replies · 821 views
10 years ago

Hi,

I would like to filter content based on type; I saw the Collection::ofType($type) filter that seems to do what I expect.

But I can't manage to use it so far to display the 5 latest classified :

TWIG
        {% set latest_classified = page.collection({
                'items': '@root.descendants',
                'order': {
                    'by': 'date',
                    'dir': 'desc'
                },
                'limit': 5,
                'ofType':'classified',
            })
        %}

On collection page, there is a PHP example but I would like to keep in a Twig universe:

PHP
$collection = new Collection();
$collection->setParams(['taxonomies' => ['tag' => ['dog', 'cat']]])->dateRange('01/01/2016', '12/31/2016')->published()->ofType('blog-item')->order('date', 'desc');

Thanks,
Nicolas

10 years ago

The other syntax that would look good to me would be:

TWIG
        {% set latest_classified = page.collection({
                'items': {
                    'ofType': 'classified',
                },
                'order': {
                    'by': 'date',
                    'dir': 'desc',
                },
                'limit': 5,
            })
%}

But it does not work either.

10 years ago

Ok, this works:

TWIG
{% for child in page.children.order('date', 'desc').ofType('album') %}
...
{% endfor %}

So seems my issue is more on the way I build my collection before the filter applies.

10 years ago

Ok found the right syntax :-D

TWIG
        {% set latest_classified = page.collection({
                'items': '@root.descendants',
                'order': {
                    'by': 'date',
                    'dir': 'desc',
                },

            })
            .ofType('classified')
            .slice(0,5)
        %}

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1351 9 years ago
Archive · by Muut Archive, 9 years ago
2 935 9 years ago
Archive · by Muut Archive, 9 years ago
2 4062 9 years ago
Archive · by Muut Archive, 9 years ago
1 2948 9 years ago
Archive · by Muut Archive, 9 years ago
3 1119 9 years ago