Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 349
xster Avatar asked Apr 20 '11 15:04

xster


People also ask

What is partial Django?

You can pass data to the partial, and use it as you would in a regular template. It is different from Django's {% include %} , because it allows you to pass a custom variable (context), instead of reusing the same context for the included template.

What is return render in Django?

In Django, render() is one of the most used functions that combines a template with a context dictionary and returns an HttpResponse object with the rendered text.

What is Django template language?

What is Django Template Language? Django Template Language or DTL is a text-based Template language that provides a bridge between scripts like HTML, CSS, JS, etc. and programming languages like python. DTL is specifically built for developers to embed Django logic codes into HTML template files.

What is render to string in Django?

Rendering means interpolating the template with context data and returning the resulting string. The Django template language is Django's own template system. Until Django 1.8 it was the only built-in option available.


2 Answers

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

like image 169
Alireza Savand Avatar answered Sep 21 '22 11:09

Alireza Savand


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 %} 
like image 24
Michael Bylstra Avatar answered Sep 21 '22 11:09

Michael Bylstra