48

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

xster
  • 6,269
  • 9
  • 55
  • 60

4 Answers4

74

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

Alireza Savand
  • 3,462
  • 3
  • 26
  • 36
41

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 %}
Michael Bylstra
  • 5,042
  • 4
  • 28
  • 24
16

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.

Marshall Davis
  • 3,337
  • 5
  • 39
  • 47
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
  • But this only lets me embed templates in templates and not views in templates. Suppose I have 10 layers of nesting, then all the variables needed for the 10 layers need to be set up in the first layer of the view before rendering the first layer... or put view logic in the template files in the middle layers – xster Apr 20 '11 at 17:05
  • 2
    nevermind, you're talking about http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/. So I can load any methods – xster Apr 20 '11 at 17:25
5

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.

utapyngo
  • 6,946
  • 3
  • 44
  • 65