开发者

Django - use template tag and 'with'?

开发者 https://www.devze.com 2022-12-27 17:52 出处:网络
I have a custom template tag: def uploads_for_user(user): uploads = Uploads.object开发者_JAVA技巧s.filter(uploaded_by=user, problem_upload=False)

I have a custom template tag:

def uploads_for_user(user):
    uploads = Uploads.object开发者_JAVA技巧s.filter(uploaded_by=user, problem_upload=False)
    num_uploads = uploads.count()
    return num_uploads

and I'd like to do something like this, so I can pluralize properly:

{% with uploads_for_user leader as upload_count %}
    {{ upload_count }} upload{{ upload_count|pluralize }}
{% endwith %}

However, uploads_for_user leader doesn't work in this context, because the 'with' tag expects a single value - Django returns:

TemplateSyntaxError at /upload/
u'with' expected format is 'value as name'

Any idea how I can get round this?


You could turn it into a filter:

{% with user|uploads_for as upload_count %}


While a filter would still work, the current answer to this question would be to use assignment tags, introduced in Django 1.4.

So the solution would be very similar to your original attempt:

{% uploads_for_user leader as upload_count %}
{{ upload_count }} upload{{ upload_count|pluralize }}

Update: As per the docs assignment tags are deprecated since Django 1.9 (simple_tag can now store results in a template variable and should be used instead)


In Django 1.9 django.template.Library.assignment_tag() is depricated: simple_tag can now store results in a template variable and should be used instead.

So, now simple tag we can use like a:

It’s possible to store the tag results in a template variable rather than directly outputting it. This is done by using the as argument followed by the variable name. Doing so enables you to output the content yourself where you see fit:

{% get_current_time "%Y-%m-%d %I:%M %p" as the_time %}
<p>The time is {{ the_time }}.</p>
0

精彩评论

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