28

I have two lists:

  1. strainInfo, which contains a dictionary element called 'replicateID'
  2. selectedStrainInfo, which contains a dictionary element called 'replicateID'

I'm looking to check if the replicateID of each of my strains is in a list of selected strains, in python it would be something like this:

for strain in strainInfo:
    if strain.replicateID in [selectedStrain.replicateID for selectedStrain in selectedStrainInfo]
        print('This strain is selected')

I'm getting the correct functionality in django, but I'm wondering if there's a way to simplify using a list comprehension:

{% for row in strainInfo %}
    {% for selectedStrain in selectedStrainsInfo %}
       {% if row.replicateID == selectedStrain.replicateID %} 
           checked 
       {% endif %}
    {% endfor %}
{% endfor %}
nven
  • 1,047
  • 4
  • 13
  • 22

2 Answers2

19

List comprehensions are not supported in Jinja

You could pass the data, via Jinja, to JavaScript variables like so

var strainInfo = {{strainInfo|safe}};
var selectedStrainInfo = {{selectedStrainInfo|safe}};

and then do your clean up there.

Use Jinja's safe filter to prevent your data from being HTML-escaped.

congusbongus
  • 13,359
  • 7
  • 71
  • 99
tmthyjames
  • 1,588
  • 2
  • 22
  • 30
17

Since v2.7 there is selectattr:

Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding.

If no test is specified, the attribute’s value will be evaluated as a boolean.

Example usage:

{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}

Similar to a generator comprehension such as:

(u for user in users if user.is_active)
(u for user in users if test_none(user.email))

See docs.

Honza Javorek
  • 8,566
  • 8
  • 47
  • 66