Question

I can't figure out how to access environment.filters. In standart Jinja2 examples I can see an example of datetimeformat filter:

def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
    return value.strftime(format)

Then we can add the filter:

environment.filters['datetimeformat'] = datetimeformat

But I attached django_jinja application and now use a standart render_to_response method from django.shortcuts (Jinja's macros, built-in functions work OK). So my views make such responses:

return render_to_response( html_template, result_dict )

I only included Jinja2 app and don't worry about constructing custom Jinja2 response, but I don't know how to access the environment.

What should I change to add a custom template filter with django_jinja application?

Here is a description of the app: https://pypi.python.org/pypi/django-jinja/0.8.

Was it helpful?

Solution

I used this...

jinja2.filters.FILTERS['datetimeformat'] = datetimeformat

Hope this helps!

OTHER TIPS

I realize that this question is fairly old but having looked around for the solution to this problem and having not found any useful answers on SO, I'd like to share my findings from the django_jinja documentation here.

There are two use cases:

  1. Registering filters globally in your Django project's settings.py. This can be done when jinja2 is specified as a template engine in the TEMPLATES setting eg.

    TEMPLATES = [
    {
        "BACKEND": "django_jinja.backend.Jinja2",
        "APP_DIRS": True,
        "OPTIONS": {
            "match_extension": ".jinja",
            "filters": {
                "myfilter": "path.to.filters.myfilterfn",
                ...
            }
        }
    }]
    

    More details incuding specifying custom extensions, context processors etc. can be obtained from this page.

  2. Registering app specific filters when creating a reusable Django app. Here again, django_jinja comes to the rescue by letting you register filters to the global library of filters as follows,

    from django_jinja import library
    @library.filter
    def mylower(name):
    """
    Usage: {{ 'Hello'|mylower() }}
    """
    return name.lower()
    

    More details here

Both examples above have been lifted as is from the django_jinja docs. Using 2 of course means that django_jinja is a dependency for your reusable app but if like me, you use Jinja templates for nearly all of your Django apps, this is not that big a deal.

Also we collect filters manually, if we want they live in one file. Update JINJA2_FILTERS dictionary (usually placed in settings.py):

# settingsutils.py
import filters # our file of filters
import inspect

def collect_j2_filters( JINJA2_FILTERS ):
""" Collects JINJA2 filters
"""

exclude_prefix = '_'

funcs = inspect.getmembers( filters, inspect.isfunction )

for f in funcs:
    name = f[ 0 ]
    callable = f[ 1 ]

    if name.find( exclude_prefix ) != 0: # filter function is found
        JINJA2_FILTERS.update( { name[ len_prefix: ]: callable } )  


# settings.py
from settingsutils import collect_j2_filters

JINJA2_FILTERS = {}
collect_j2_filters( JINJA2_FILTERS )

After that we can place all filter functions to filters.py file of a main project catalog. collect_js_filters retrieves all the functions which don't started with _.

You can use django-jinja to easily do this:

In <someapp>/templatetags/<anyfile>.py you simply do

from django_jinja import library

@library.filter
def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
    return value.strftime(format)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top