1
0
mirror of https://github.com/django/django.git synced 2025-10-29 00:26:07 +00:00

Fixed #23914 -- Improved {% now %} to allow storing its result in the context.

Thanks to Tim for the review.
This commit is contained in:
Baptiste Mispelon
2014-11-25 19:24:57 +01:00
parent 3a9aa155e2
commit c335c0fee9
4 changed files with 31 additions and 3 deletions

View File

@@ -419,12 +419,19 @@ class LoadNode(Node):
class NowNode(Node):
def __init__(self, format_string):
def __init__(self, format_string, asvar=None):
self.format_string = format_string
self.asvar = asvar
def render(self, context):
tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None
return date(datetime.now(tz=tzinfo), self.format_string)
formatted = date(datetime.now(tz=tzinfo), self.format_string)
if self.asvar:
context[self.asvar] = formatted
return ''
else:
return formatted
class SpacelessNode(Node):
@@ -1200,10 +1207,14 @@ def now(parser, token):
It is {% now "jS F Y H:i" %}
"""
bits = token.split_contents()
asvar = None
if len(bits) == 4 and bits[-2] == 'as':
asvar = bits[-1]
bits = bits[:-2]
if len(bits) != 2:
raise TemplateSyntaxError("'now' statement takes one argument")
format_string = bits[1][1:-1]
return NowNode(format_string)
return NowNode(format_string, asvar)
@register.tag