开发者

Django how to partial render

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


I think you're looking for {% include '_partial.html' %}.


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:

{% include 'partials/blog_entry.html' with blog_entry=my_blog_entry %}


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.


I have adapted this snippet and made it available as a pypi package.

  1. pip install django_render_partial

  2. Add 'django_render_partial' to INSTALLED_APPS

  3. Ensure that 'django.template.context_processors.request' is in TEMPLATES['OPTIONS']['context_processors']

  4. Use {% render_partial %} tag in your template:

{% load render_partial %}

{# using view name from urls.py #}    
{% render_partial 'partial_view' arg1=40 arg2=some_var %}

{# using fully qualified view name #}
{% render_partial 'partial_test.views.partial_view' arg1=40 arg2=some_var %}

{# class based view #}
{% render_partial 'partial_test.views.PartialView' arg1=40 arg2=some_var %}

A test project containing these examples is available on GitHub.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜