Move the sorting logic to a separate method, so we can apply the sorting outside the template context