Back

Randomize a Query and Sort

Description

This code snippet shows how to take a content pull, randomize the list for a specific number of results and then sort the randomized list afterward.

If the size of the list is less than the number to show, it doesn't do anything as it doesn't make sense to randomize and sort a list that will be the same as the previous list that was sorted on the content pull.

Code

## Setup values
#set($num_to_show = 10)
#set($item_list = $dotcontent.pull("$query_string",0,"StructureName.fieldToSortOn asc"))

## Check the length of the array. 
## If array is shorter than the number to show, it doesn't make sense to randomize because you will
## get back the same results and then sort those (just extra overhead for dotCMS)
## Only randomize if you have more results than the the number you want to display
#if($item_list.size() > $num_to_show)
	## Randomize and Sort the accumulated list
	#set($item_list = $UtilMethods.randomList($item_list, $num_to_show))
	#set($item_list = $sorter.sort($item_list, ['attribute1', 'attribute2']))
#end