How to iterate through a list of dictionaries in Jinja template?

Data: parent_list = [{‘A’: ‘val1’, ‘B’: ‘val2’}, {‘C’: ‘val3’, ‘D’: ‘val4’}] in Jinja2 iteration: {% for dict_item in parent_list %} {% for key, value in dict_item.items() %} <h1>Key: {{key}}</h1> <h2>Value: {{value}}</h2> {% endfor %} {% endfor %} Note: Make sure you have the list of dict items. If you get UnicodeError may be the value … Read more

Get lengths of a list in a jinja2 template

<span>You have {{products|length}} products</span> You can also use this syntax in expressions like {% if products|length > 1 %} jinja2’s builtin filters are documented here; and specifically, as you’ve already found, length (and its synonym count) is documented to: Return the number of items of a sequence or mapping. So, again as you’ve found, {{products|count}} … Read more

zip(list1, list2) in Jinja2?

Modify the jinja2.Environment global namespace itself if you see fit. import jinja2 env = jinja2.Environment() env.globals.update(zip=zip) # use env to load template(s) This may be helpful in separating view (template) logic from application logic, but it enables the reverse as well. #separationofconcerns

Create dynamic arguments for url_for in Flask

Any arguments that don’t match route parameters will be added as the query string. Assuming extra_args is a dict, just unpack it. extra_args = {‘hello’: ‘world’} url_for(‘doit’, oid=oid, **extra_args) # /doit/123?hello=world url_for(‘doit’, oid=oid, hello=’davidism’) # /doit/123?hello=davidism Then access them in the view with request.args: @app.route(‘/doit/<int:oid>’) def doit(oid) hello = request.args.get(‘hello’) …

Update and render a value from Flask periodically

Using an Ajax request Python @app.route(‘/_stuff’, methods= [‘GET’]) def stuff(): cpu=round(getCpuLoad()) ram=round(getVmem()) disk=round(getDisk()) return jsonify(cpu=cpu, ram=ram, disk=disk) Javascript function update_values() { $SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; $.getJSON($SCRIPT_ROOT+”/_stuff”, function(data) { $(“#cpuload”).text(data.cpu+” %”) $(“#ram”).text(data.ram+” %”) $(“#disk”).text(data.disk+” %”) }); } Using Websockets project/app/views/request/websockets.py # -*- coding: utf-8 -*- # OS Imports import json # Local Imports from app … Read more

Comments not working in jinja2

Basically, jinja2 is only concerned with finding an evaluating its own blocks, not the structure of the HTML. If you want to exclude a section of your template entirely, you can use jinja2’s comment syntax: {# This is a comment now. <div class=”control-group”> … </div> #}