Django 如何部分渲染
如何从模板级别调用视图方法(例如 RoR 中的部分渲染)?这个博客完美地说明了这个问题。我可以使用 include 将模板包含在模板中,但随后我必须匹配模板层之间的所有变量名称。我真的很想在模板中包含视图并解耦层。该博客是一年前写的。从那以后有更好的解决方案吗?
谢谢
How do I call a view method from a template level like partial render in RoR? The problem is perfectly illustrated in this blog. I can use include to include templates in templates but then I would have to match all the variable names across layers of templates. I really would want to include views in templates and decouple layers. The blog was written a year ago. Is there a better solution since?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您正在寻找
{% include '_partial.html' %}
。I think you're looking for
{% include '_partial.html' %}
.https://docs.djangoproject.com/en/ dev/ref/templates/builtins/?from=olddocs#include
如果在包含部分内容时使用“with”参数,则不需要匹配变量 - 您可以在包含模板之前重命名变量。我发现这种技术使我能够创建更多可重用的模板。而且,它比创建包含标签的工作量要少得多。例如:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include
If you use the 'with' argument when including a partial, you don't need to match variables - You can rename a variable before including a template. I've found this technique enables me to create far more reusable templates. Also it is much less work than creating inclusion tags. Eg:
模板标签绝对是 Django 中实现此目的的方法。如果您需要将特定内容传递给模板并让它呈现内容,则可以使用内置包含标记,该标记接受传递给它们的变量。
现在,使用 包含标签,您可以指定要渲染的模板的路径。 Django 不会像 Rails 那样自动查找
/your_app/views/_my_partial.html.erb
。查看文档,看看是否能满足您的需要。如果没有,您可以随时编写自己的。
Template tags are definitely the way to do this in Django. If you need to pass specific things to a template and just have it render the contents, you can use the built-in inclusion tags, which accept variables passed to them.
Now, with inclusion tags, you have to specify the path to the template to render. Django won't automatically find
/your_app/views/_my_partial.html.erb
like in Rails.Check out the docs and see if that will do what you need. If not, you can always write your own.
我已经改编了此代码段并将其作为pypi 包。
pip install django_render_partial
将
'django_render_partial'
添加到INSTALLED_APPS
确保
'django.template.context_processors.request'
位于TEMPLATES['OPTIONS']['context_processors']
中
使用
{%模板中的 render_partial %}
标记:A 测试项目 可在 GitHub 上找到。
I have adapted this snippet and made it available as a pypi package.
pip install django_render_partial
Add
'django_render_partial'
toINSTALLED_APPS
Ensure that
'django.template.context_processors.request'
is inTEMPLATES['OPTIONS']['context_processors']
Use
{% render_partial %}
tag in your template:A test project containing these examples is available on GitHub.