Ticket #13730: needs_context.diff

File needs_context.diff, 2.1 KB (added by Suor, 5 years ago)
  • django/template/__init__.py

     
    566566                    arg_vals.append(mark_safe(arg))
    567567                else:
    568568                    arg_vals.append(arg.resolve(context))
    569             if getattr(func, 'needs_autoescape', False):
     569            if getattr(func, 'needs_context', False):
     570                new_obj = func(obj, context=context, *arg_vals)
     571            elif getattr(func, 'needs_autoescape', False):
    570572                new_obj = func(obj, autoescape=context.autoescape, *arg_vals)
    571573            else:
    572574                new_obj = func(obj, *arg_vals)
     
    801803
    802804    def render(self, context):
    803805        return self.s
    804    
     806
    805807def _render_value_in_context(value, context):
    806808    """
    807809    Converts any value to a string to become part of a rendered template. This
  • docs/howto/custom-template-tags.txt

     
    305305       handle the auto-escaping issues and return a safe string, the
    306306       ``is_safe`` attribute won't change anything either way.
    307307
     308Context filters
     309~~~~~~~~~~~~~~~~~~~~~~~~~
     310
     311.. versionadded:: 1.2
     312
     313Filters can behave diffrently depending on context. To make your filter get
     314context, set the ``needs_context`` attribute to ``True`` on your function
     315For example, this filter will transform given time to time zone specified
     316in context:
     317
     318    import pytz
     319    from django.conf import settings
     320
     321    def localtime(dt, context=None):
     322        if dt.tzinfo is None:
     323            dt = pytz.timezone(settings.TIME_ZONE).localize(dt)
     324        return dt.astimezone(context['timezone'])
     325    localtime.needs_context = True
     326
     327Of course, the 'timezone' key should be written into context to use it.
     328Also, you can't use both ``needs_context`` and ``needs_autoescape``.
     329
    308330Writing custom template tags
    309331----------------------------
    310332
Back to Top