Django template iterating over list - python

I have a list created in Django view:
list = [ elem1, elem2, ..., elemN ]
The list is variable length: it can contain 0-6 elements. I want to iterate over the list in the template, but I would like the loop to run always 6 times, yielding None or empty string for non-existing elements.
I tried something like this:
{% for i in "0123456" %}
{{ list.i }}
{% endfor %}
but this obviously doesn't work. I know I could do this in the view, but I would like to have this in the template. Is is possible?

You can add an if statement checking if it is your 6th time through the loop.
{% for item in someList %}
{% if forloop.counter <= 6 %}
{{ item }}
{% endif %}
{% endfor %}
http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#for in the docs.
Of course, if your list is very long then this is not optimal. I would also suggest processing the list in views.py and then passing it to the template. Logic should stay in the views if possible.
This gives you control over the number of loops done. To completely solve your problem you will need some addtional logic but see my note above regarding this.

Check this snippet: Template range filter

Related

Django template loop where last item value is not Null

DB data:
pk,text
2|null
3|foo
4|null
5|bar
6|null
I intend to loop the given data, but I only want to iterate over items where text column value is NOT null. Also, I need to know which is the last value where text column is NOT null.
This is my intended view once the template has rendered:
3 foo
5 bar *last*
In python, such is achieved by an if condition in list comprehension, such as:
[x for x in my_loop if x != None]
Rendering this in the views.py is massively inconvenient due to how this data is also used in the rest of the template, and this would also gobble up too much unnecessary memory.
However, is this possible to do when rendering in django template?
Many thanks!
This should work.
{% for item in items %}
{% if item.text %}
<span>{{ item.text }}</span>
{% endif %}
{% endfor %}

Dealing with json type data in a template

I am after some advice. I know what I need to do, but not sure how I can do it
I send data to a template that comes from from a database
Let's say the database has two fields
Field one (name)
Name of a person
Field two some json (the json has a structure like this, with many field:value)
{
"field1":"value1",
"field2":"value2"
}
I can output this as
Field one (name) Field two (json)
What I actually want to do though, is loop through the json, and print out the values, so like this
Name of a person field1|field2
I am a bit lost on how I can do that
I tried something like this
{% for anitem in fieldtwo %}
<div>{{ anitem }}</div>
{% endfor %}
But that just seems to print out each character
Is what I need to do achievable? I am thinking I just have the whole approach wrong
Thanks
Grant
In the end, I ended up using another dictionary and then pass that through to the template
I loop through the queryset in the view to populate the dictionary
In the template I then did this (alloweddomains is from the view)
{% for testcaseid, domains in alloweddomains.items %}
{% if listtestcase.id == testcaseid %}
{% for key, value in domains.items %}
<div><a class="sendtolinkdisabled" data-testcasename="{{ listtestcase.name }}" data-testcaseid="{{ $
{% endfor %}
{% endif %}
{% endfor %}
This basically looped through the dictionary and if there was a match to my unique ID I get the data and do something with it
I tried various ways to not need the if statement and just get the right point in the dictionary, but nothing seemed to work (so I took the if approach)
Grant

Creating a list from CSV value in Jinja

In a flask template, I'd like to loop over my values which is a comma separated range of values. So in my template, I'd like to do something like:
{% for tag in list(myparent.my_tags) %}
{{tag}}
{% endfor %}
I can see list in the documents, but I don't see how to use it. http://jinja.pocoo.org/docs/dev/templates/
The value of my_tags is abc, def, ghi,... and the aim to loop over each group in turn.
Jinja2's split function should work.
{% for tag in myparent.my_tags.split(',') %}
{{ tag }}
{% endfor %}

Checking if something exists in items of list variable in Django template

I have a list of sections that I pass to a Django template. The sections have different types. I want to say "if there is a section of this type, display this line" in my template, but having an issue. What I'm basically trying to do is this.
{% if s.name == "Social" for s in sections %}
Hello Social!
{% endif %}
But of course that's not working. Any idea how to basically in one line loop through the items in a list and do an if statement?
ADDITIONAL INFO: I could potentially have multiple "Social" sections. What I'm trying to do in the template is say "if there are any social sections, display this div. If not, don't display the div." But I dont want the div to repeat, which is what would happen with the above code.
Ideally what you would do is create a list that the template gets as such:
l = [s.name for s in sections]
And in the template, use:
{% if 'Social' in l %}
You're trying to put more logic into a template than they are meant to have. Templates should use as little logic as possible, while the logic should be in the code that fills the template.
You can't use list comprehensions in templates:
{% for s in sections %}
{% if s.name == 'Social' %}
Hello Social!
{% endif %} {# closing if body #}
{% endfor %} {# closing for body #}
{% if sections.0.name == "Social" %}
Hello Social!
{% endif %}

django template question (accessing a list)

I am writing a template for my first django website.
I am passing a list of dictionaries to the template in a variable. I also need to pass a few other lists which hold boolean flags. (Note: all lists have the same length)
The template looks something like this:
<html>
<head><title>First page</title></head><body>
{% for item in data_tables %}
<table>
<tbody>
<tr><td colspan="15">
{% if level_one_flags[forloop.counter-1] %}
<tr><td>Premier League
{% endif %}
<tr><td>Junior league
<tr><td>Member count
{% if level_two_flags[forloop.counter-1] %}
<tr><td>Ashtano League
{% endif %}
</tbody>
</table>
{% endfor %}
</body>
</html>
I am getting the following error:
Template error
In template /mytemplate.html, error at
line 7 Could not parse the remainder:
'[forloop.counter-1]' from
'level_one_flags[forloop.counter-1]'
I am, not suprised I am getting this error, since I was just trying to see if would work. So far, from the documentation, I have not found out how to obtain the items in a list by index (i.e. other than by enumeration).
Does anyone know how I may access a list by index in a template?
In short, Django doesn't do what you want.
The for loop has a number of useful properties within a loop.
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
forloop.revcounter The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
forloop.first True if this is the first time through the loop
forloop.last True if this is the last time through the loop
forloop.parentloop For nested loops, this is the loop "above" the current one
You could probably use forloop.counter0 to get the zero-based indexes you want; unfortunately, the Django template language doesn't support variable array indexes (You can do {{ foo.5 }}, but you can't do {{ foo.{{bar}} }}).
What I usually do is to try and arrange the data in the view to make it easier to present in the template. As an example, for you could create an array in your view composed of dictionaries so that all you have to do is loop through the array and pull exactly what you need out of the individual dictionaries. For really complicated things, I've gone so far as to create a DataRow object that would correctly format the data for a particular row in a table.
You use the dot-operator to index the array, or, really, to do anything.
Technically, when the template system
encounters a dot, it tries the
following lookups, in this order:
* Dictionary lookup
* Attribute lookup
* Method call
* List-index lookup
I don't believe you can do math on the index. You'll have to pass in your array constructed in some other way so that you don't have to do this subtraction.
Try using "slice" to access a list by index
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#slice
Perhaps a better way is to use forloop.last. Of course, this will require that you send to the template the specific level_one_flag and level_two_flag out of the level_one_flags and level_two_flags arrays, but I think this solution keeps a better logical separation between view and template:
<html>
<head><title>First page</title></head><body>
{% for item in data_tables %}
<table>
<tbody>
<tr><td colspan="15">
{% if forloop.last and level_one_flag %}
<tr><td>Premier League
{% endif %}
<tr><td>Junior league
<tr><td>Member count
{% if forloop.last and level_two_flag %}
<tr><td>Ashtano League
{% endif %}
</tbody>
</table>
{% endfor %}
</body>
</html>

Categories