开发者

How can you use Django template tags in a Jinja2 template?

There are a number of off-the-shelf Django packages that offer template tags, and I'd like to use them in my project despite the fact that it uses Jinja2.

I've seen some workarounds that allow other template engines to use Django tags. These involve creating a mini-template in a string, and passing it to the Django template processor along with the current context. Here are two example of what I'm talking about: Mako templates using Django template tags and Jinja2 templates using Dj开发者_StackOverflow中文版ango template tags.

I'm wondering if there's a less hackish solution.


what about moving problem to python's scope and importing one python's function into another, this way:

in your_jinja_templatetags.py

from some_django_templatetags import somefilter as base_somefilter

@library.filter
def somefilter(value):
   return base_somefilter(value)


Unfortunately Django template tags are not directly translatable to Jinja.

Django Template tags can do many different things, and are usually implemented as functions. Fortunately, Jinja can register these functions as globals and call them. This works for "simple" template tags out of the box.

If you are using the official Django Jinja2 backend, see https://docs.djangoproject.com/en/4.1/topics/templates/#django.template.backends.jinja2.Jinja2 to find out how to register a function (in this case your template tag) as a global. Once this is done, you can call the function from within your template as {{ your_tag_function() }}. Remember to pass whatever arguments the template tag function needs!

I like to use the https://github.com/niwinz/django-jinja backend, myself- if you are using this backend, see https://niwi.nz/django-jinja/latest/#_custom_filters_globals_constants_and_tests for how to register a function as a global.

Unfortunately, this only works for "simple" tags out of the box. Some tags are "inclusion tags" or otherwise depend on the Django Template Engine. Since Django Templates can't be rendered within the Jinja engine, you have to do a bit more work to translate these types of tags. You will need to look at the source code to tell the difference and see what they are doing.

What I usually do for the more complicated tags is create a "jinja_functions.py" script in my Django app, then in that script I import the original template tag. Then I write a function that wraps it- calling the original function, getting back usually a dictionary, and then using that dict to render a string which is returned... most tags are simple enough I just use an f string or .format to format them with the results of the dict.

Then I register my new wrapper function as a jinja global and use it in my jinja templates!

The following is an example of where I re-implemented the template tags provided by https://github.com/timonweb/django-tailwind for use with jinja. I combined both the tailwind_css and tailwinf_preload_css tags into a single function, tailwind_css, which I register with Jinja as a global as per the instructions above, then I can call that function as {{ tailwind_css(prefetch=True) }} or {{ tailwind_css() }} within my templates.

from django.templatetags.static import static
from tailwind import get_config
from tailwind.utils import is_path_absolute

def tailwind_css(v=None, prefetch=False):

    tailwind_css_path = get_config("TAILWIND_CSS_PATH")
    if not is_path_absolute(tailwind_css_path):
        tailwind_css_path = static(tailwind_css_path)
    if v:
        tailwind_css_path = f"{tailwind_css_path}?v={v}"
    if prefetch:
        rel = 'rel="preload"'
        as_str = ' as="style"'
    else:
        rel = 'rel="stylesheet"'
        as_str = ""

    return f'<link {rel} href="{tailwind_css_path}"{as_str}>'

In conclusion it works well out of the box for "simple" tags because you can just register them as global functions in Jinja... but for "include" tags or other tags that rely on the Django Template engine, you will have to write your own function :( But usually its not too much work!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜