using a loop result as a variable for child loop - django

I think the best way to describe is problem is with an example.
{% for content in contents %}
{% for stuff in {{content}} %}
{{stuff}}
{% endfor %}
{% endfor %}
I am using google app engine webapp templates. I can't seem to use a result from the parent forloop {{content}} as a variable for its child forloop. TemplateSyntaxError: Could not parse the remainder: '{{content}}' from '{{content}}' Is it possible to do this? Thanks!!

You can use only content without braces around:
{% for content in contents %}
{% for stuff in content %}
{{ stuff }}
{% endfor %}
{% endfor %}
When you are inside the first for-loop, content exists in the context, as any other variable. Same thing for stuff in the inner loop. Plus, blocks are generally using argument as variables, except in it is surrounded by quotes.
The {{ }} notation can be use to only display the variable in the document.

Related

Update variables passed with django include tag

I have a for loop that contains an include tag like the following:
{% for thing in things %}
{% block example %}
{% include 'myapp/example.html' with thing=thing %}
{% endblock %}
{% endfor %}
I expected that the html in example.html would get rendered with each thing within things but it only gets rendered with the first thing object. Is there a way to pass each of the thing objects within things to example.html?
Your code is supposed to work, even with the {% block %} tags, as long as you do not redefine them somewhere else. Maybe the problem is on the things or myapp/example.html side?
Note: if you refer to thing with the same identifier in your child template, you don't need the with thing=thing part - for exemple, {{ thing }} will be directly avalaible in your child template.
Something you might want to try:
{% for thing in things %}
{% include 'myapp/example.html' %}
{{ thing }}
{% endfor %}

Jinja2 templating with components? blocks? templates?

A little question to jinja2 templating:
I want to create a reusable template to include and then overwrite blocks. Macros do not let me write junks of HTML easily as parameters do they? Say I want to reuse an include several times and am using BIG junks of HTML in blocks that I want to dynamically assign
how would I do it?
certainly not with macros I guess, or am I wrong?
{% render_foo('bar',2) %} is fine
{% render_foo('<table><tr><th>something</th><th>somethingelse</th></tr><tbody><tr>....etc') %} is not fine any more is it
"what do you really want to do?"
yes, what I told you, I have a way I create containers for my data. The container is ALWAYS the same. The content is completely different on each usage. Once a table. Once a bootstrap component. Once a form.
The surrounding elements are always the same
to reproduce the simple error this is what I did:
{% include 'full_section.html' %}
{% block fullsection %} <table><tr><th>something</th><th>somethingelse</th></tr><tbody><tr>....etc{% endblock %}
{% include 'full_section.html' %}
{% block fullsection %} <form>//some cool LONG big form </form>{% endblock %}
full_section.html contents just for completeness, it is a lot more complex in reality
<div class="my_cool_full_section">
{% block full_section %}{% endblock %}
</div>
TemplateAssertionError: block 'fullsection' defined twice
I found the answer well hidden in the jinja2 docs
http://jinja.pocoo.org/docs/2.9/templates/#block-assignments
so you use a macro and a block assignment e.g. like this:
{% set section_content %}
<table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table>
<table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table>
<table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table>
{% endset %}
{{ render_full_size_section(section_content) }}
{% set section_content %}
aaaaaaaaaaa
{% endset %}
{{ render_full_size_section(section_content) }}
wonder what they were doing pre 2.8... dark dark middle age
then in the macro:
{% macro render_full_size_section(content) %}
<div class="mycoolsection">
{{ content | safe }}
</div>
{% endmacro %}

Is it possible in Jinja2 to have this behaviour?

I have a list of strings that I will process and for brevity sake I am writing them as spans here.
I want some html to go inside a div, so,
<div class="something">
<span>something1</span>
<span>something2</span>
<span>something3</span>
...
</div>
And some other outside (depending on some condition)
<span>something-else1</span>
<span>something-else2</span>
<span>something-else3</span>
...
So the condition comes from something in the list. Is there any way so I can stop the control at a macro caller so I can have the same macro be called again so it would append the next span in the same place?
So something like
{% macro render_inside_div %}
<div class="something">
{{ caller() }} <-- I want to render multiple spans in within the same div
</div>
{% endmacro %}
EDIT:
Yes, of course that would work and that is (sort of) how I got it to work anyways. But I was looking for a 'cleaner' and DRY solution. So basically I would just iterate the list once and the way it would work would be something like this:
{% for row in my_list %}
{% if row.condition_for_div %}
{% call render_in_div %} {# Look before to see the macro I've written above #}
{{ do_something(row.data) }}
{% endcall %}
{% else %}
{{ do_something(row.data) }}
{% endif %}
{% endfor %}
so in this render_in_div I want to hand control to the caller() block many times, so the control (for that "context") would remain there until I say to get out (in some way like a generator?)

django template: how to enclose a variable

I would like to make a sequence of variables within a for loop such as name0, name1, .... How do I do that? Thanks.
{% for i in '1234567890' %}
{% if name{{forloop.counter0}} %}
...
{% endif %}
...
{{name{{forloop.counter0}}}}
...
{% endfor %}
is as simple as
{{ name }}{{ forloop.counter0 }}
for the if, you should use the "with" statement:
{% with name|add:forloop.counter0 as if_test %}
{% if if_test %}
... <!-- do whatever you need to do here -->
all this must be inside your for loop
As you can see, the Django templating language tries hard to keep you from doing what you're trying to do, encouraging you to do your data processing in your view code, instead of your templates. For your example, in your view code, you might try doing:
context['names'] = [name for name in names[:10]]
...instead of creating individual variables for each name.
Then in your template:
{% for name in names %}
{% if name %}
...
{% endif %}
...
{{name}}
...
{% endfor %}
As far as I can tell, that would have the same effect as your code, but you would be doing your aggregation of the names in the view, instead of the template. If I'm reading the intent of your code wrongly, please provide more context, but it doesn't seem like you're doing anything that requires template logic.

Django template for loop. Member before

I want to create such loop:
{% for object in objects %}
{% if object.before != object %}
{{ object }} this is different
{% else %}
{{ object }} this is the same
{% endfor %}
Based on https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#for I can't. Is there really no simple way to do this? Or I just need to use counter and check for objects[counter-1]?
P.S. .before is theoretical and objects is simple query list. I want to take and do something with the loop member that encountered before current loop member.
Check ifchanged template tag
There is a "simple way" to do this: write a custom template tag. They're really not hard. This would probably do the trick (untested):
#register.simple_tag
def compare_objects(object_list):
comparisons = []
for i in range(1, len(object_list)):
if object_list[i] > object_list[i-1]:
comparisons.append('bigger')
else:
comparisons.append('smaller')
return comparisons
The built-in template tags and filters don't make it easy (as of Django 1.4), but it is possible by using the with tag to cache variables and the add, slugify, and slice filters to generate a new list with only one member.
The following example creates a new list whose sole member is the previous member of the forloop:
{% for item in list %}
{% if not forloop.first %}
{% with forloop.counter0|add:"-1" as previous %}
{% with previous|slugify|add:":"|add:previous as subset %}
{% with list|slice:subset as sublist %}
<p>Current item: {{ item }}</p>
<p>Previous item: {{ sublist.0 }}</p>
{% endwith %}
{% endwith %}
{% endwith %}
{% endif %}
{% endfor %}
This isn't an elegant solution, but the django template system has two faults that make this hack unavoidable for those who don't what to write custom tags:
Django template syntax does not allow nested curly parenthesis. Otherwise, we could do this:
{{ list.{{ forloop.counter|add:-1 }} }}
The lookup operator does not accept values stored using with (and perhaps for good reason)
{% with forloop.counter|add:-1 as index %}
{{ list.index }}
{% endwith %}
This code should work just fine as a django template, as long as object has a property or no-argument method called before, and objects is iterable (and '<' is defined).
{% for object in objects %}
{% if object.before < object %}
this is bigger
{% else %}
this is smaller
{% endfor %}