How to use 3rd party app templatetags with Jinja 2?

别来无恙 提交于 2019-12-30 08:15:27

问题


I am trying Jinja2 for my Django website.

Now, since Jinja2 is not official Django templating engine and its refusing to recognise / load the template tags I was using prior to Jjinja2.

Now, even if there has to be a change in the template tags creation, then how is it possible to reflect across the 3rd party apps?

In that case it seems impossible to use Jinja2 since the system has to work as per Jinja2.

(I am also using coffin as an adapter for Jinja-Django).


回答1:


According to coffin docs you will have to rewrite any custom django templates tags as custom Jinja2 extensions.

You could also use jinja2 macros feature to emulate the Django's template tags. The most notable difference is that for Jinja2 macros it will be necessary to provide all the context data via the template context, while in Django tags you can access data using other ways (like loading from the database or calling other Python libraries).

I've been using Jinja2 templates for a while and never had a need to create a custom template tag.

It is possible to use django templates in one app on the site and jinja2 in another app, it is not a problem, but it is not readily possible to import or extend jinja2 templates from django templates and vs versa.




回答2:


You can do this with coffin. Coffin supplies a way to register django-style tags to use within jinja2 templates:

from coffin import template
from ThrdPartyDjangoLib import djangoTagIWantToUse
register = template.Library()

register.tag('djangoTagIWantToUse', djangoTagIWantToUse)



回答3:


Django's structure does not allow for swapping the template engine since it is a core part of the system. Even if you can by using coffin, it is not a supported configuration and no third-party module can be expected to support it. It would be same as asking third party modules to support sqlalchemy because you found a way to make django work with it.

If you want to use jinja2, use a framework that is designed with a pluggable template engine - or one that comes without a template engine.

The integration page lists out of the box integrations that come with Jinja2. On that page you can see that Pyramid is supported - and that is because by design pyramid allows for pluggable components.

Flask (made by the same people behind Jinja2) has native support for Jinja2.



来源:https://stackoverflow.com/questions/10949388/how-to-use-3rd-party-app-templatetags-with-jinja-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!