sum
Totals the named field across a slice of maps, the way you sum one column of a list of records.
A field absent from a record is a miss, so
| sum:'amount' | default:0 falls back rather than failing, while a
non-numeric value in the column is a terminal error, since silently treating
"abc" as zero would understate a total that someone is going to act on.
InputArgumentsReturns
Source[]anystringfloat64[]anyno argumentsfloat64Behaviors
- Catchable miss
- When the data it looks for is not there, it reports a miss rather than failing the render, so
defaultcan supply a fallback and aniforforreads the absence as false.
BasicSource
Totals the named field across a slice of maps.
Given
{"items": [{"name": "Mug", "price": 10}, {"name": "Cup", "price": 8}]}Template
{{ items | sum:'price' }}Result
18DecimalsSource
Totals a field holding fractional amounts.
Given
{"items": [{"name": "Mug", "price": 10.5}, {"name": "Cup", "price": 4.25}]}Template
{{ items | sum:'price' }}Result
14.75NegativeSource
Totals a field that mixes positive and negative numbers.
Given
{"entries": [{"amount": 10}, {"amount": -3}]}Template
{{ entries | sum:'amount' }}Result
7BasicSource
Adds up the elements of a slice, returning a number.
Given
{"prices": [10, 8, 4]}Template
{{ prices | sum }}Result
22EmptySource
Sums an empty slice to zero.
Given
{"amounts": []}Template
{{ amounts | sum }}Result
0StringsSource
Sums numeric strings, parsing each before adding.
Given
{"amounts": ["1.5", "2.5", "6"]}Template
{{ amounts | sum }}Result
10