Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehensions in Jinja

Tags:

python

jinja2

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 %}
like image 607
nven Avatar asked May 19 '16 15:05

nven


People also ask

What is block content in Jinja?

All the block tag does is tell the template engine that a child template may override those placeholders in the template. In your example, the base template (header. html) has a default value for the content block, which is everything inside that block. By setting a value in home.

How are variables in Jinja2 templates specified?

A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine. A template contains variables and/or expressions, which get replaced with values when a template is rendered; and tags, which control the logic of the template.


2 Answers

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.

like image 188
tmthyjames Avatar answered Sep 16 '22 18:09

tmthyjames


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.

like image 24
Honza Javorek Avatar answered Sep 17 '22 18:09

Honza Javorek