Search code examples
nulljinja2return-valueminimum

Minimum value Jinja


I have a Jinja template with a table that has 5 columns for each row. Column 1 to 4 are variable string representation of numbers (floating point decimal), column 5 shows the minimum value of these 4 columns using the following code;

{{ ['1', '2', '3', '4'] | min }}

This works fine, as long as all 4 of the columns are populated. Once one of the columns is empty nothing is returned.

{{ ['1', '2', '3', ''] | min }}

Is there a way to fix this?


Note: the original question mentioned a list of integer [1, 2, 3 ,4] but after pretty printing them, I realised those were actually string representation of integers.


Solution

  • Since your pprint showed you that you do have string representation of integers — '1' — and not integers — 1 — in your variables, what you can, now, do is to reject the empty strings.

    For extra care, I also thrown a map of the trim filter, so, if you have a blank string — e.g. with only spaces — then, this case will also be covered up.

    So, given:

    {{ ['1', '2', '', '4', ' '] | map('trim') | reject('eq','') | min }}
    

    This gives the expected: '1'


    If you do have integers, you can select only the numeric values out of a list with the select filter and the number test.

    Given:

    • {{ [1, 2, None, 4] | select('number') | min }}
      

    Or

    • {{ [1, 2, '', 4] | select('number') | min }}
      

    Those both yield 1 as you would expect it.