mirror of https://github.com/django/django.git
Fixed #14262 -- Added new assignment_tag as a simple way to assign the result of a template tag to a context variable. Thanks, Julien Phalip.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@16149 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
8ce352c21d
commit
950e05c3ff
|
@ -901,6 +901,66 @@ class Library(object):
|
|||
else:
|
||||
raise TemplateSyntaxError("Invalid arguments provided to simple_tag")
|
||||
|
||||
def assignment_tag(self, func=None, takes_context=None):
|
||||
def dec(func):
|
||||
params, xx, xxx, defaults = getargspec(func)
|
||||
if takes_context:
|
||||
if params[0] == 'context':
|
||||
params = params[1:]
|
||||
else:
|
||||
raise TemplateSyntaxError("Any tag function decorated with takes_context=True must have a first argument of 'context'")
|
||||
|
||||
class AssignmentNode(Node):
|
||||
def __init__(self, params_vars, target_var):
|
||||
self.params_vars = map(Variable, params_vars)
|
||||
self.target_var = target_var
|
||||
|
||||
def render(self, context):
|
||||
resolved_vars = [var.resolve(context) for var in self.params_vars]
|
||||
if takes_context:
|
||||
func_args = [context] + resolved_vars
|
||||
else:
|
||||
func_args = resolved_vars
|
||||
context[self.target_var] = func(*func_args)
|
||||
return ''
|
||||
|
||||
def compile_func(parser, token):
|
||||
bits = token.split_contents()
|
||||
tag_name = bits[0]
|
||||
bits = bits[1:]
|
||||
params_max = len(params)
|
||||
defaults_length = defaults and len(defaults) or 0
|
||||
params_min = params_max - defaults_length
|
||||
if (len(bits) < 2 or bits[-2] != 'as'):
|
||||
raise TemplateSyntaxError(
|
||||
"'%s' tag takes at least 2 arguments and the "
|
||||
"second last argument must be 'as'" % tag_name)
|
||||
params_vars = bits[:-2]
|
||||
target_var = bits[-1]
|
||||
if (len(params_vars) < params_min or
|
||||
len(params_vars) > params_max):
|
||||
if params_min == params_max:
|
||||
raise TemplateSyntaxError(
|
||||
"%s takes %s arguments" % (tag_name, params_min))
|
||||
else:
|
||||
raise TemplateSyntaxError(
|
||||
"%s takes between %s and %s arguments"
|
||||
% (tag_name, params_min, params_max))
|
||||
return AssignmentNode(params_vars, target_var)
|
||||
|
||||
compile_func.__doc__ = func.__doc__
|
||||
self.tag(getattr(func, "_decorated_function", func).__name__, compile_func)
|
||||
return func
|
||||
|
||||
if func is None:
|
||||
# @register.assignment_tag(...)
|
||||
return dec
|
||||
elif callable(func):
|
||||
# @register.assignment_tag
|
||||
return dec(func)
|
||||
else:
|
||||
raise TemplateSyntaxError("Invalid arguments provided to assignment_tag")
|
||||
|
||||
def inclusion_tag(self, file_name, context_class=Context, takes_context=False):
|
||||
def dec(func):
|
||||
params, xx, xxx, defaults = getargspec(func)
|
||||
|
|
|
@ -681,7 +681,70 @@ Or, using decorator syntax::
|
|||
return your_get_current_time_method(timezone, format_string)
|
||||
|
||||
For more information on how the ``takes_context`` option works, see the section
|
||||
on `inclusion tags`_.
|
||||
on :ref:`inclusion tags<howto-custom-template-tags-inclusion-tags>`.
|
||||
|
||||
.. _howto-custom-template-tags-assignment-tags:
|
||||
|
||||
Assignment tags
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
.. versionadded:: 1.4
|
||||
|
||||
Another common type of template tag is the type that fetches some data and
|
||||
stores it in a context variable. To ease the creation of this type of tags,
|
||||
Django provides a helper function, ``assignment_tag``. This function works
|
||||
the same way as :ref:`simple_tag<howto-custom-template-tags-simple-tags>`,
|
||||
except that it stores the tag's result in a specified context variable instead
|
||||
of directly outputting it.
|
||||
|
||||
Our earlier ``current_time`` function could thus be written like this:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_current_time(format_string):
|
||||
return datetime.datetime.now().strftime(format_string)
|
||||
|
||||
register.assignment_tag(get_current_time)
|
||||
|
||||
The decorator syntax also works:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@register.assignment_tag
|
||||
def get_current_time(format_string):
|
||||
...
|
||||
|
||||
You may then store the result in a template variable using the ``as`` argument
|
||||
followed by the variable name, and output it yourself where you see fit:
|
||||
|
||||
.. code-block:: html+django
|
||||
|
||||
{% get_current_time "%Y-%m-%d %I:%M %p" as the_time %}
|
||||
<p>The time is {{ the_time }}.</p>
|
||||
|
||||
If your template tag needs to access the current context, you can use the
|
||||
``takes_context`` argument when registering your tag:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# The first argument *must* be called "context" here.
|
||||
def get_current_time(context, format_string):
|
||||
timezone = context['timezone']
|
||||
return your_get_current_time_method(timezone, format_string)
|
||||
|
||||
register.assignment_tag(takes_context=True)(get_current_time)
|
||||
|
||||
Or, using decorator syntax:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@register.assignment_tag(takes_context=True)
|
||||
def get_current_time(context, format_string):
|
||||
timezone = context['timezone']
|
||||
return your_get_current_time_method(timezone, format_string)
|
||||
|
||||
For more information on how the ``takes_context`` option works, see the section
|
||||
on :ref:`inclusion tags<howto-custom-template-tags-inclusion-tags>`.
|
||||
|
||||
.. _howto-custom-template-tags-inclusion-tags:
|
||||
|
||||
|
|
|
@ -52,6 +52,14 @@ documentation for :attr:`~django.contrib.admin.ModelAdmin.list_filter`.
|
|||
A lazily evaluated version of :func:`django.core.urlresolvers.reverse` was
|
||||
added to allow using URL reversals before the project's URLConf gets loaded.
|
||||
|
||||
Assignment template tags
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
A new helper function,
|
||||
:ref:`assignment_tag<howto-custom-template-tags-assignment-tags>`, was added to
|
||||
``template.Library`` to ease the creation of template tags that store some
|
||||
data in a specified context variable.
|
||||
|
||||
.. _backwards-incompatible-changes-1.4:
|
||||
|
||||
Backwards incompatible changes in 1.4
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
from __future__ import with_statement
|
||||
|
||||
from django import template
|
||||
from django.utils.unittest import TestCase
|
||||
from templatetags import custom
|
||||
|
@ -102,3 +104,54 @@ class CustomTagTests(TestCase):
|
|||
|
||||
c.use_l10n = True
|
||||
self.assertEquals(t.render(c).strip(), u'True')
|
||||
|
||||
def test_assignment_tags(self):
|
||||
c = template.Context({'value': 42})
|
||||
|
||||
t = template.Template('{% load custom %}{% assignment_no_params as var %}The result is: {{ var }}')
|
||||
self.assertEqual(t.render(c), u'The result is: assignment_no_params - Expected result')
|
||||
|
||||
t = template.Template('{% load custom %}{% assignment_one_param 37 as var %}The result is: {{ var }}')
|
||||
self.assertEqual(t.render(c), u'The result is: assignment_one_param - Expected result: 37')
|
||||
|
||||
t = template.Template('{% load custom %}{% assignment_explicit_no_context 37 as var %}The result is: {{ var }}')
|
||||
self.assertEqual(t.render(c), u'The result is: assignment_explicit_no_context - Expected result: 37')
|
||||
|
||||
t = template.Template('{% load custom %}{% assignment_no_params_with_context as var %}The result is: {{ var }}')
|
||||
self.assertEqual(t.render(c), u'The result is: assignment_no_params_with_context - Expected result (context value: 42)')
|
||||
|
||||
t = template.Template('{% load custom %}{% assignment_params_and_context 37 as var %}The result is: {{ var }}')
|
||||
self.assertEqual(t.render(c), u'The result is: assignment_params_and_context - Expected result (context value: 42): 37')
|
||||
|
||||
self.assertRaisesRegexp(template.TemplateSyntaxError,
|
||||
"'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
|
||||
template.Template, '{% load custom %}{% assignment_one_param 37 %}The result is: {{ var }}')
|
||||
|
||||
self.assertRaisesRegexp(template.TemplateSyntaxError,
|
||||
"'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
|
||||
template.Template, '{% load custom %}{% assignment_one_param 37 as %}The result is: {{ var }}')
|
||||
|
||||
self.assertRaisesRegexp(template.TemplateSyntaxError,
|
||||
"'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
|
||||
template.Template, '{% load custom %}{% assignment_one_param 37 ass var %}The result is: {{ var }}')
|
||||
|
||||
def test_assignment_tag_registration(self):
|
||||
# Test that the decorators preserve the decorated function's docstring, name and attributes.
|
||||
self.verify_tag(custom.assignment_no_params, 'assignment_no_params')
|
||||
self.verify_tag(custom.assignment_one_param, 'assignment_one_param')
|
||||
self.verify_tag(custom.assignment_explicit_no_context, 'assignment_explicit_no_context')
|
||||
self.verify_tag(custom.assignment_no_params_with_context, 'assignment_no_params_with_context')
|
||||
self.verify_tag(custom.assignment_params_and_context, 'assignment_params_and_context')
|
||||
|
||||
def test_assignment_tag_missing_context(self):
|
||||
# That the 'context' parameter must be present when takes_context is True
|
||||
def an_assignment_tag_without_parameters(arg):
|
||||
"""Expected __doc__"""
|
||||
return "Expected result"
|
||||
|
||||
register = template.Library()
|
||||
decorator = register.assignment_tag(takes_context=True)
|
||||
|
||||
self.assertRaisesRegexp(template.TemplateSyntaxError,
|
||||
"Any tag function decorated with takes_context=True must have a first argument of 'context'",
|
||||
decorator, an_assignment_tag_without_parameters)
|
||||
|
|
|
@ -84,3 +84,33 @@ def use_l10n(context):
|
|||
@register.inclusion_tag('test_incl_tag_use_l10n.html', takes_context=True)
|
||||
def inclusion_tag_use_l10n(context):
|
||||
return {}
|
||||
|
||||
@register.assignment_tag
|
||||
def assignment_no_params():
|
||||
"""Expected assignment_no_params __doc__"""
|
||||
return "assignment_no_params - Expected result"
|
||||
assignment_no_params.anything = "Expected assignment_no_params __dict__"
|
||||
|
||||
@register.assignment_tag
|
||||
def assignment_one_param(arg):
|
||||
"""Expected assignment_one_param __doc__"""
|
||||
return "assignment_one_param - Expected result: %s" % arg
|
||||
assignment_one_param.anything = "Expected assignment_one_param __dict__"
|
||||
|
||||
@register.assignment_tag(takes_context=False)
|
||||
def assignment_explicit_no_context(arg):
|
||||
"""Expected assignment_explicit_no_context __doc__"""
|
||||
return "assignment_explicit_no_context - Expected result: %s" % arg
|
||||
assignment_explicit_no_context.anything = "Expected assignment_explicit_no_context __dict__"
|
||||
|
||||
@register.assignment_tag(takes_context=True)
|
||||
def assignment_no_params_with_context(context):
|
||||
"""Expected assignment_no_params_with_context __doc__"""
|
||||
return "assignment_no_params_with_context - Expected result (context value: %s)" % context['value']
|
||||
assignment_no_params_with_context.anything = "Expected assignment_no_params_with_context __dict__"
|
||||
|
||||
@register.assignment_tag(takes_context=True)
|
||||
def assignment_params_and_context(context, arg):
|
||||
"""Expected assignment_params_and_context __doc__"""
|
||||
return "assignment_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)
|
||||
assignment_params_and_context.anything = "Expected assignment_params_and_context __dict__"
|
||||
|
|
Loading…
Reference in New Issue