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

查看:25
本文介绍了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天全站免登陆