开发者

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 开发者_JAVA技巧%}
{% endfor %}

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


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.


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.


Yes, you can use the with construct:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜