如何在 Jinja 2 中使用 3rd 方应用模板标签? [英] How to use 3rd party app templatetags with Jinja 2?

查看:18
本文介绍了如何在 Jinja 2 中使用 3rd 方应用模板标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的 Django 网站尝试 Jinja2.

现在,由于 Jinja2 不是官方的 Django 模板引擎,它拒绝识别/加载我在 Jjinja2 之前使用的模板标签.

现在,即使模板标签的创建必须发生变化,那么如何才能在第 3 方应用中反映出来?

在那种情况下,似乎不可能使用 Jinja2,因为系统必须按照 Jinja2 运行.

(我也使用 coffin 作为 Jinja-Django 的适配器).

解决方案

根据 棺材文档您必须将任何自定义 django 模板标签重写为自定义 Jinja2 扩展.

您还可以使用 jinja2 宏功能来模拟 Django 的模板标签.最显着的区别是,对于 Jinja2 宏,需要通过模板上下文提供所有上下文数据,而在 Django 标签中,您可以使用其他方式(如从数据库加载或调用其他 Python 库)访问数据.

我使用 Jinja2 模板已有一段时间了,从未需要创建自定义模板标签.

可以在站点上的一个应用程序中使用 django 模板,在另一个应用程序中使用 jinja2,这不是问题,但是从 django 模板导入或扩展 jinja2 模板并不容易,反之亦然.

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).

解决方案

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.

这篇关于如何在 Jinja 2 中使用 3rd 方应用模板标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆