user7331530
user7331530

Reputation: 985

How do I sort items in an object in Freemarker

Built in sort and sort_by in Freemarker is for list. How Do I sort object in Freemarker?

<#assign myObject = {
    'item1':{'name': 'Name One', 'url': 'https://www.one.com, 'order': 1},
    'item2':{'name': 'Name Two', 'url': 'https://www.two.com, 'order': 2},
    'item3'...
}/>


<#macro displayobjectLinks>
    <ul>
        <#list objectLinks?keys as info>
            <#if (info != "item1")>
                <li><a href="${objectLinks[info].url}">${objectLinks[info].name}</a></li>
            </#if>
        </#list>
    </ul>
</#macro?

How do I display this in order based on 'order'?
I also need to access key of my object(item1, item2...) as I am doing something based on it.

Upvotes: 4

Views: 12508

Answers (2)

Abdul Najeeb Khan
Abdul Najeeb Khan

Reputation: 55

sort_by

Returns the sequence of hashes sorted by the given hash sub variable in ascending order. (For descending order use this and then the reverse built in.) The rules are the same as with the sort built-in, except that the sub variables of the sequence must be hashes, and you have to give the name of a hash sub variable that will decide the order. For example:

In your case you can use the below code :

<#list objectLinks?sort_by("name") as info>

</#list>

Upvotes: 5

Jasper de Vries
Jasper de Vries

Reputation: 20271

Your object is a hash, which has a values built-in, which returns a sequence, which can be sorted. So, you could do something like:

<#list myObject?values?sort_by("name") as item>
</#list>

Please note that not all hashes support this though, but you will be fine.

Upvotes: 3

Related Questions