如何将动态生成的内容块放入Django模板中? [英] How can I put a block of dynamically generated content into a django template?

查看:131
本文介绍了如何将动态生成的内容块放入Django模板中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在django模板中包含诸如twitter status或美味标签之类的东西。

I want to include things like twitter status, or delicious tags, in my django templates.

这些事情是动态的,但有规律。

These things are dynamic, yet regular. How would this be done?

推荐答案

有多种处理方法,因此您可以选择最匹配的方法您自己的个人风格或要求:

There are a number of ways to handle this, so you can choose a method that best matches your own personal style or requirements:


  1. 模板上下文变量:如Alex所示,您可以输入将您的内容添加到上下文变量中,该变量包含在每个视图创建的每个模板的上下文中。 Django甚至提供了一种自动执行此操作的机制,称为上下文处理器。优点:非常简单。缺点:不会在客户端浏览器上动态刷新新内容。

  1. Template context variable: as answered by Alex you can put your content into a context variable that is included in the context of every template created by every view. Django even provides a mechanism for doing this automatically, called a context processor. Pros: very straightforward. Cons: won't dynamically refresh new content on client browsers.

AJAX动态加载:如Alex和Dave所述,您可以使用AJAX方法动态加载您的内容。作为使用jQuery的示例,您将在模板中放置一个占位符,例如< div id = twitterfeed>< / div> ,然后在javascript块中在您的模板中放入 $(#twitterfeed)。load( {%url twitterfeed%}); 其中 twitterfeed 是在您的urls.py中如此命名的网址。优点:将动态更新浏览器。缺点:如果您不懂Javascript,可能会很棘手。

AJAX dynamic loading: as mentioned by Alex and Dave you can dynamically load your content using AJAX methods. As an example using jQuery, you would put a placeholder in your template something like <div id="twitterfeed"></div> and then in a javascript block in your template put $("#twitterfeed").load("{% url twitterfeed %}"); where twitterfeed is a url so named in your urls.py. Pros: will dynamically update browsers. Cons: can be tricky if you don't know Javascript.

包含标记:Django提供了一种称为包含标签,它基本上是一个可以呈现动态内容的自定义模板标签。在某种程度上,它类似于上下文变量,只不过在您在模板中使用自定义模板标记时才会调用生成内容的代码,而不是在每个视图中都调用它。另一个好处是,内容是从其自己的模板生成的。当然,您可以使用普通的上下文变量来执行此操作,但它不如使用包含标记那么干净(IMHO)。优点:非常简单,干净。缺点:不会在客户端浏览器上动态刷新新内容。

Inclusion tag: Django provides a type of template tag called an inclusion tag, which is basically a custom template tag that can render dynamic content. In a way it's similar to a context variable, except your code to generate the content will only be called when you use the custom template tag in your template instead of being called for every view. Another benefit is the content is generated from a template of its own. You could do this with a normal context variable of course, but it's not as clean (IMHO) as using an inclusion tag. Pros: very straightforward, clean. Cons: won't dynamically refresh new content on client browsers.

这篇关于如何将动态生成的内容块放入Django模板中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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