43
votes

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

4
Good question. I'm really surprised it didn't get a lot of attention.MK_Dev
The link to the blog is broken.quapka

4 Answers

65
votes

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

37
votes

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 %}
13
votes

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.

4
votes

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.