Search code examples
gogo-html-template

Sort slice in golang html/template?


I have a slice like [{0 1} {0 3} {0 2}]. Order is random. I'd like to output them in order of second argument. {{range .Slice}} would return them in the order of indexed position. I would use something like {{range .Slice|sortBy .[1]}} but there is no such thing.

How can I get the range sorted by sub-item and context set to current item (not the sub-item) at the same time?

Expected output: 0 1 0 2 0 3

Actual output: rows are returned in random order


Solution

  • You can use a custom template function to do that.

    This question has an answer that demonstrates template function: Go template doesn't work correctly with if and range