update value of a variable inside a template - django
Asked Answered
H

1

2

I have seen enough number of examples that allow me to declare a new variable inside a template and set its value. But what I want to do is to update the value of a particular variable inside the template.

For example I have a datetime field for an object and I want to add timezone according to the request.user from the template. So I will create a template filter like {% add_timezone object.created %} and what it will do is that it will add timezone to object.created and after that whenever I access {{object.created}} it will give me the updated value.

Can anybody tell me how this can be done. I know I need to update the context variable from the template filter. But don't know how.

Hoad answered 4/7, 2012 at 8:1 Comment(3)
What have you tried so far? This is stackoverflow, not doalltheworkforme.com.Canella
Logic like this really shouldn't be in the template, you know. Why can't you do this in the view?Vitiligo
I don't want to do it in the view because there might be date field in the query set and then I will have to change the attributes in the queryset itself. Using this template tag, I can make it very genericHoad
F
2

You cannot modify a value in a template, but you can define 'scope' variables using the {% with %} tag:

{% with created=object.created|add_timezone %}
    Date created with fixed timezone: {{ created }}
{% endwith %}

where add_timezone is a simple filter:

def add_timezone(value):
    adjusted_tz = ...
    return adjusted_tz

register.filter('add_timezone', add_timezone)
Frecklefaced answered 4/7, 2012 at 12:13 Comment(4)
Thanks, seems decent enough solution, but theres one problem. I will have to use alot of with tags if there are multiple such objectsHoad
You can of course modify a value in a template, you just need to write a custom templatetag for this.Virga
@Frecklefaced Aha, this is an interesting distingo. If templatetags and filters are "out of the template", then there's not much left happening here <g>Virga
Actually you cannot modify a variable in a template even with a templatetag or filter. You can only use it(use in a calculation, filter it, render in custom html etc.). But this variable will have the same value if you use it again in the template. The only way to reuse a changed variable is with {%with%}, as a scope variable, or - yes- to write something like {% with %} that holds the variable state. So I'm using above 'value' instead of variable, maybe this is a bit confusing...Frecklefaced

© 2022 - 2024 — McMap. All rights reserved.