Django 共享模板

Posted

技术标签:

【中文标题】Django 共享模板【英文标题】:Django shared template 【发布时间】:2009-08-07 21:26:07 【问题描述】:

我正在寻找如何在 Django 的 ASP.NET 中做到最好的事情,例如 UserControl。

例如: 1) 定义了一个 Book 模型 2) 我想在我的网站上使用这本书的常规表示形式(称为“book_template.html”)。

现在假设我想从 2 个视图中使用这一表示:recent_books_view、popular_books_view。可以直接像


from django import template

t = template.Template('My name is name .') book1_context = template.Context('book': Book1) book2_context = template.Context('book': Book2) book3_context = template.Context('book': Book3) ...

render_to_response('recent_books.html', 'content': t.render(book1_context) + t.render(book2_context) + t.render(book3_context))

render_to_response('popular_books.html', 'content': t.render(book4_context) + t.render(book5_context) + t.render(book6_context))

但我确信有更好的方法......

例如,在 ASP.NET 中,您可以在模板文件中说“申请数组 'Books' 这个共享模板”,然后在后端指定变量 'Books'。这在 Django 中可行吗?

【问题讨论】:

【参考方案1】:

在你的 python 代码中:

context['books'] = blah blah # Make a list of books somehow.
return render_to_response('popular_books.html', context)

在 popular_books.html 中:

<p>Look, books:</p>
% for book in books %
    % include "book.html" %
% endfor %

最后,在 book.html 中:

<p>I am a book, my name is book.name</p>

还有更多有趣的模块化方式,比如创建自定义标签,这样你就可以,例如:

<p>Look, books:</p>
% for b in books %
    % book b %
% endfor %

【讨论】:

这就是你想要做的。您可能需要一些 Book.objects.filter(...) 来选择您的热门书籍和最近的书籍。 这是一个很好的方法。我一直将对象列表传递给我的模板。事实上,我经常有一个模板“list.html”,我的大多数其他模板都继承自该模板。 (list.html 有分页控件等常用元素。) 太好了!如何定义 % book b % 模板?【参考方案2】:

我认为您正在寻找本教程Chapter 4 of the Django book: The Django Template System。

查看块标签和模板继承。

【讨论】:

以上是关于Django 共享模板的主要内容,如果未能解决你的问题,请参考以下文章

django模板获取键和值分开显示

如何将值从 django 模板化 html 传递到 ajax

Django 中所有应用程序共享的菜单

使用 Django 模板标签的 Mako 模板

模板 Django 应用程序扩展模板 django 项目

Django框架-Django模板(template)系统