orokusaki
orokusaki

Reputation: 57118

Django - Is there a way to create a variable in the template?

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)

Upvotes: 1

Views: 278

Answers (4)

Peter Rowell
Peter Rowell

Reputation: 17713

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.

Upvotes: 2

Bialecki
Bialecki

Reputation: 31041

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.

Upvotes: 3

Steve Jalim
Steve Jalim

Reputation: 12195

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.

Upvotes: 1

Olivier Verdier
Olivier Verdier

Reputation: 49126

Yes, you can use the with construct:

{% with myvariable as egg %}
do stuf
{% endwith %}

Upvotes: 1

Related Questions