Django:内置包含标记与自定义包含标记 [英] Django: Built-in include tag vs custom inclusion tag

查看:59
本文介绍了Django:内置包含标记与自定义包含标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django的内置包含标记之间有什么区别自定义包含标签

What is the difference between Django's built-in include tag and custom inclusion tags?

我已经阅读了文档,两者似乎都实现了相同的目标:呈现一个将其传递给上下文或变量的模板。

I have read the documentation, and both seem to to achieve the same goal: render a template passing it a context or variable.

推荐答案

它们有不同的用途。 include 标签只是简单地完整地包含了来自现有模板的内容,并且未经修改。自定义包含标签将上下文传递给函数,该函数可以包含在将上下文传递给模板之前对其进行操作的逻辑。

They serve different purposes. The include tag simply includes the content from an existing template in its entirety and unmodified. A custom inclusion tag passes the context to a function which can contain logic to manipulate the context before passing it to a template.

例如,也许我有一个面板在多个页面上显示。面板的模板需要通过上下文传递一些特定的查询。包含面板的页面不需要其他任何上下文变量。如果我在面板模板中添加 include 标记,则必须在包含该面板的每个视图中编写这些查询,并将其作为上下文变量传递。

For example, perhaps I have a panel that will be shown on multiple pages. The panel's template requires a few specific queries to be passed to it through the context. The pages that contain the panel don't require those context variables for anything else. If I include the panel template with the include tag, I would have to write those queries in every view that contains the panel and pass them as context variables.

或者,我可以编写一个包含查询的自定义包含标签并将其传递到面板的模板。通过使用自定义包含标记,我无需在包含面板的每个视图中重复代码来生成其上下文。我的视图将包含更少的代码,并且只会被面板使用的上下文变量所干扰。

Alternatively, I could write a custom inclusion tag that contains the queries and passes them to the panel's template. By using the custom inclusion tag I wouldn't need to repeat the code to produce its context in every view that contains the panel. My views would contain less code and would be less cluttered with context variables only used by the panel.

尽管您的看法是正确的,但自定义包含标记只是通过了在未操作的上下文中与 include 标记相同。

Although you are correct in the sense that a custom inclusion tag that simply passes on the context unmanipulated would be the same as the include tag.

这篇关于Django:内置包含标记与自定义包含标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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