Group and Sort Data in Latte Like a Pro

7 months ago by David Grudl  

In the latest update of Latte, we are introducing several significant enhancements that will simplify and make more efficient the work with data in your templates. The new |group filter and the expanded capabilities of the |sort filter bring new possibilities for data presentation.

The |group filter is a tool that allows you to group data according to specified criteria, which is ideal for dividing items into categories or subcategories directly in your Latte templates. For example, you can easily group items by category using the following syntax:

{foreach ($items|group: categoryId) as $categoryId => $categoryItems}
	<ul>
		{foreach $categoryItems as $item}
			<li>{$item->name}</li>
		{/foreach}
	</ul>
{/foreach}

It is exceptionally interesting when combined with Nette Database. For more detailed information, visit the page Everything you ever wanted to know about grouping.

While the |group filter will help you with organizing data, the expanded |sort filter now allows you to sort your data even more effectively. Thanks to the new parameters by and byKey, you can specify by which key or value you want to sort the elements:

{foreach ($items|sort: by: 'name') as $item}
	{$item->name}
{/foreach}

For a deeper understanding and more examples, visit the documentation |sort. Get ready for your templates to be even more powerful!