'Empty string when accessing dictionary value in Jinja2
Trying to add the value of item['val'] to the table results in empty space
item.num is a list of numbers that is shown as an integer on the table, where as item.val is a float number that needs to be shown as is on the table
app.py
@app.route('/')
def index():
items = Item.query.filter_by().all()
# item.num is a list of items
# item.val is a float value
tmp = {"item_num":item.num , "item_val":str(item.val)}
result[item.name] = tmp
return render_template("information.html", info=result)
information.html
<thead>
<tr>
<th scope="col">name</th>
<th scope="col">item num</th>
<th scope="col">item val</th>
</tr>
</thead>
<tbody>
{% for item in info %}
<tr>
<td>{{ item }}</td>
<td>{{ item['num'] | length }}</td>
<td>{{ item['val'] }}</td>
</tr>
{%endfor%}
</tbody>
how do you add a value from the dictionary to the table
Solution 1:[1]
If I understand you correctly, you have a dict with a nested dict, like in this example. The name of an item represents the key value under which further data is stored. Since you don't mention your second table in your code, I can't refer to that one.
@app.route('/')
def index():
items = Item.query.all()
result = { item.name: {'num': item.num, 'val':str(item.val)} for item in items }
return render_template('information.html', info=result)
So you can iterate over all key-value pairs with the keyword items() and then query the data from the nested dict.
<thead>
<tr>
<th scope="col">name</th>
<th scope="col">item num</th>
<th scope="col">item val</th>
</tr>
</thead>
<tbody>
{% for k,v in info.items() %}
<tr>
<td>{{ k }}</td>
<td>{{ v['num'] | length }}</td>
<td>{{ v['val'] }}</td>
</tr>
{%endfor%}
</tbody>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Detlef |
