views:

59

answers:

4

I want to do this:

{% for egg in eggs %}
    <p>{{ egg.spam }}</p>
    {% if egg.is_cool %}
        {% myvariable = egg %} // Possible in any way?
    {% endif %}
{% endfor %}

Pardon the JavaScript-style comment (it shows up as a comment on SO)

+3  A: 

I think the closest you'll get is the with tag: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#with.

If you're say trying to feature an item in a template, I can imagine doing something like:

<div class="special">
{% with some_list.first as special_item %}
    {{ specialitem }}
{% endwith %}
</div>

<div class="everything">
{% for item in some_list %}
    {{ item }}
{% endfor %}
</div>

If you want some special logic to determine which one is the special item, I'd add a method to the object (so you end up with: {% with some_collection.my_method as special_item %} above) or determine the special item before passing it to the view. Hope that helps.

Bialecki
@Bialecki Basically, the reason for creating a variable is to use it outside of the loop. The `with` tag is a loop itself. I need to later access `myvariable` later in the page.
orokusaki
+1  A: 

Yes, you can use the with construct:

{% with myvariable as egg %}
do stuf
{% endwith %}
Olivier
@Olivier The only problem is: `The populated variable (in the example above, total) is only available between the {% with %} and {% endwith %} tags.`
orokusaki
+1  A: 

I think it's probably best to do this kind of test-and-set behaviour in the view, not the template. If anything, it'll give you better control over cacheing if/when you need it.

stevejalim
@stevejalim The problem with doing that is that I need to do this in all of my views.
orokusaki
if you really need to do it in ALL of your views you could create a decorator or some middleware to encapsulate whatever the logic is that you need.
Matthew J Morrison
+2  A: 

Welcome to Django Templates.

This problem is easily solved with one of the earliest snippets posted to DjangoSnippets.com: the Expr tag.

People can argue all day about the separation of logic from the templates, but that ignores that there is business logic, which belongs in the models or views, and presentation logic which belongs only in the templates. If you have a lot of presentation logic you may want to consider using Jinja2 for some or all of your templates. WARNING: although Jinja2 looks a lot like Django's template language, there are incompatibilities with things like Custom Template Tags.

Peter Rowell
Thanks Peter. I've been considering using Cheetah, but never really thought about using Jinja. I think the reason is that I currently use Velocity, but now that I'm accustomed to using Django templates' style and syntax, Jinja might be a fine addition.
orokusaki