velocityxwiki

Can this list be sorted by date in Velocity?


I've found this code for getting articles by tag and display them as a list with links in xWiki, but I want it sorted by date.

Has anyone a suggestion for me?

  {{velocity}}  
    #set ($list = $xwiki.tag.getDocumentsWithTag('myTag'))
      #foreach($reference in $list)
    #set ($document = $xwiki.getDocument($reference))
    #set ($label = $document.getTitle())
      [[$label>>$reference]]
    #end
  {{/velocity}}

Thanks in advance!


Solution

  • Sorting in velocity can hit one of 2 performance penalties:

    1. Actually sorting in velocity, either with a sorting algorithm -> unnecesarrily compicated
    2. Loading all the document results into memory (a collection) and sorting that collection with the sort/collection tool -> you risk quickly running out of memory if the result is larger than you expected.

    The easiest alternative, given that there is XWiki running behind it, would be to do an XWQL query for the XWiki.TagClass objects stored inside the documents and do the sorting at the database level. At this point, in velocity, you only need to display the results:

    {{velocity}}
    #foreach ($docStringRef in $services.query.xwql("from doc.object(XWiki.TagClass) tagsObj where 'conference' member of tagsObj.tags order by doc.creationDate DESC").setLimit(10).execute())
      #set ($document = $xwiki.getDocument($docStringRef))
      [[$document.title>>$docStringRef]]
    #end
    {{/velocity}}
    

    For future use/reference, the list of available Velocity tools in XWiki might also be useful https://extensions.xwiki.org/xwiki/bin/view/Extension/Velocity%20Module#HVelocityTools since they can help with common operations, including sorting (that I mentioned at point 2. above)