Django 共享模板
我正在寻找如何在 Django 中做最好的事情,比如 ASP.NET 中的 UserControl。
例如: 1)定义了一个Book模型 2)我想在我的网站上使用这本书的常规表示(称为“book_template.html”)。
现在假设我想使用 2 个视图中的这一表示:recent_books_view、popular_books_view。 可以像这样直接完成
from django import template
t = template.Template('我的名字是 {{ 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',
{'内容': t.render(book1_context) + t.render(book2_context) + t.render(book3_context)})
render_to_response('popular_books.html',
{'内容':t.render(book4_context)+ t.render(book5_context)+ t.render(book6_context)})
但我确信有更好的方法......
例如,在 ASP.NET 中,您可以在模板文件中说“申请数组'Books'这个共享模板”,然后在后端您只需指定变量'Books'。 这在 Django 中可能吗?
I'm looking how to do the best something like a UserControl in ASP.NET in Django.
For example:
1) There's a Book model defined
2) There's a regular representation of the book which I want to use all over my site (called "book_template.html").
Now let's say I want to use this one representation from 2 views: recent_books_view, popular_books_view. It can be done directly like
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)})
But I'm sure there's a better way...
For example, in ASP.NET you can say in template file "apply for array 'Books' this shared template", and then in the backend you just specify variable 'Books'. Is that possible in Django?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在你的Python代码中:
在popular_books.html中:
最后,在book.html中:
有更有趣的模块化方法,例如创建自定义标签,这样你就可以:
In your python code:
In popular_books.html:
Finally, in book.html:
There are more interesting ways to modularize, such as creating a custom tag, so that you could, for example:
我想您正在寻找本教程 Django 书的第 4 章:Django 模板系统。
请参阅块标签和模板继承。
I think you're looking for this tutorial Chapter 4 of the Django book: The Django Template System.
See block tags and template inheritance.