Hello I am using jinja2 and I have a list of dictionaries that I am passing to jinja template.
{%for dict in list_of_dicts%}
<tr>
{%for key in my_dict.keys()%}
<td> {{my_dict.key}}</td> // Here i want to get value in my_dict with that particular key.
{%endfor%}
</tr>
{%endfor %}
How do I achieve this?
By using just one variable in your for-loop, you just get the value and not the key name. You can use the alternative key, value syntax (as documented here) in a for loop to get the keys in a separate variable, like this:
{% for key, value in my_dict.iteritems() %}
<td>{{ key }}</td>
{% endfor %}
Related
I am following this video and everything is working perfectly. The output of a SQL query is saved within a variable that I can call on in another .html page.
so my sql query is:
#app.route('/all_data')
def all_data():
customers = db.get_customers()
for customer in customers:
var = customers
return render_template('all_data.html',var=var)
When calling this {{var}} in all_data.html page the output is for a long tuple:
('name','email','comment','gender'),('name','email','comment','gender') etc etc
I am looking to put this {{var}} into a table instead?.. I but am hitting a brick wall in finding out how to do this?
any help would be much appreciated!
Assuming you're using Flask's default template engine (Jinja2), you can simple use a for loop to iterate over the elements of the collection inside the template. The syntax is:
{% for item in items %}
{{ item }}
{% endfor %}
So simply create an HTML table, and add a row for each item in your var variable.
IIRC, Jinja tuples act the same as Python's, so you can probably do something along the lines of:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Comment</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
{% for current in var %}
<tr>
<td>{{ current[0] }}</td>
<td>{{ current[1] }}</td>
<td>{{ current[2] }}</td>
<td>{{ current[3] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I haven't checked it (as I don't have a Flask project available right now), but if my memory serves me right, that's how I would do it
Here's a link to an usefull part of Jinja2's documentation
Also, what is this piece of code for ?
for customer in customers:
var = customers
You're iterating over each element of the list, but your never use the customer variable (containing the current element). Instead, you assign the var variable to the customers list multiple times. Assuming customers is a simple Python list, you could remove this loop and simply do return render_template('all_data.html',var=customers)
I have a dictionary that I pass to Django template.
If I render just a dictionary with {{dict}} , then it is rendered fine, like this:
If I render just the keys with {{appoint}}, they are also rendered just fine, like this:
But if I render dictionary values with {{dict.appoint}} then I get nothing
I have read every post here about Django, template language and dictionaries and have not been able to solve this seemingly simple problem.
Render your dict in html like this:
{% for key, value in dict.items() %}
<tr>
<td> {{ key }}: </td> <td> {{ value }} </td>
</tr>
{% endfor %}
you can do with a custom template tag, check in here how to do it https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/
I have recently tried to solve the challenge of handling a dynamic number of columns in my Django template (essentially working through a list containing lists that isnt standerdized).
I pass two things to my view:
test_array: an array that looks something like the following [[1,2,3],[1,2,3],[1,2,3]]
numbers: in this case 3 (indicating the number of attributes in the sub lists
I thought to solve this as follows:
<tbody>
{% for t in test_array %}
<tr>
{% for x in numbers %}
<td>{{ t.x }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
But the above returns no output. When I reference t.1, t.2 etc hardcoded this returns output.
As such, what is the best way to handle a dynamic number of columns in Django? Or, is there a more elegant way to solve the above?
Passing the length of the sublists to the the template isn't necessary.
As the list elements are also lists the inner loop could simply be reduced to this:
{% for x in t %}
<td>{{ x }}</td>
{% endfor %}
My List
book_details = [
{'author':'abc', 'book_name':'xyz', 's_no':1},
{'author':'efg', 'book_name':'ijk', 's_no':2}
]
My code:
{% for dict in details %}
<tr>
{% for key, value in dict.items %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
Output :
Author Book_name S_no
Desired output:
S_no Book_name Author
I'm new to django , please guide.
Right now you are iterating through each key-value pair in the dictionary, so your code is outputting dictionary values in the order in which they are stored in the dictionary, which happens to be:
Author Book_name S_no
So, you have two options.
Change the order in which these attributes are stored in the dictionary. If you change the structure of your dictionaries from {'author': 'abc', 'book_name':'xyz','s_no':1} to {'s_no':1, 'book_name':'xyz', 'author': 'abc'}, iterating over the key-value pairs will return these attributes in the desired order. However, this is not a very flexible solution, so I would suggest the second option.
Change the way you output dictionary values. Instead of iterating through all the key-value pairs in whatever order they happen to be in, you can explicitly define the order in which you want to output dictionary values by changing this:
{% for key,value in dict.items %}
<td>{{value}}</td>
{% endfor %}
to this:
{% for key in ['S_no', 'Book_name', 'Author'] %}
<td>{{dict[key]}}</td>
{% end for %}
This solution has the added benefit of being quite easy to modify if, later on, you decide you want to output these values in another order.
{% for dict in details %}
<tr>
<td>{{dict.s_no}}</td>
<td>{{dict.book_name}}</td>
<td>{{dict.author}}</td>
</tr>
{% endfor%}
I am trying to retrieve the value of a dictionary key and display that on the page in a Django template:
{% for dictkey in keys %}
<p> {{ mydict.dictkey }} </p>
{% endfor %}
(let's say 'keys' and 'mydict' have been passed into the template in the Context)
Django renders the page but without the dictionary contents ("Invalid template variable")
I assume the problem is that it is trying to do mydict['dictkey'] instead of mydict[actual key IN the variable dictkey]? How does one "escape" this behavior?
Thanks!
UPDATE:
Based on the answers received, I need to add that I'm actually looking specifically for how to achieve a key lookup inside a for loop. This is more representative of my actual code:
{% for key, value in mydict1.items %}
<p> {{ mydict2.key }} </p>
{% endfor %}
Basically, I have two dictionaries that share the same keys, so I can't do the items() trick for the second one.
See this answer to a (possibly duplicate) related question.
It creates a custom filter that, when applied to a dictionary with a key as it's argument, does the lookup on the dictionary using the key and returns the result.
Code:
#register.filter
def lookup(d, key):
if key not in d:
return None
return d[key]
Usage:
{% for dictkey in dict1.keys %}
<p> {{ dict2|lookup:dictkey }} </p>
{% endfor %}
Registering the filter is covered in the documentation.
I find it sad that this sort of thing isn't built in.
From http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
The trick is that you need to call dict.items() to get the (key, value) pair.
See the docs: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}