How to test for a List in Jinja2?

后端 未结 4 1206
生来不讨喜
生来不讨喜 2021-01-03 18:33

As far as I can see, there is no way to test if an object is a List instance in Jinja2.

Is that correct and has anyone implemented a custom test/extensio

4条回答
  •  死守一世寂寞
    2021-01-03 19:13

    In my setup, I'd like for a value to either be a string or list of strings coming into the Jinja template. So really what I cared about wasn't string vs list, but single item vs multiple items. This answer might help if your use case is similar.

    Since there isn't a built-in test for "is list?" that also rejects strings, I borrowed a pattern from API design and wrapped the single objects in a list on the Python side then checked list length on the Jinja side.

    Python:

    context = { ... }
    
    # ex. value = 'a', or ['a', 'b']
    if not isinstance(value, list):
        value = [value]
    
    context['foo'] = value
    

    Jinja:

    {% if foo|length == 1 %}
      single-item list
    {% elif foo|length > 1 %}
      multi-item list
    {% endif %}
    

    And if all you want to do is add an item separator for display purposes, you can skip the explicit length check and just {{ value|join(', ') }}.

提交回复
热议问题