Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Rendering Inclusion Tag from a View

so I was wondering if you could return an inclusion tag directly from a view.

The page is a normal page with a list of items. The list of items is rendered using an inclusion tag. If an ajax request is made to the view, I want to return only what the inclusion tag would return so I can append it onto the page via javascript. Is something like this possible? Or should I architect this better?

like image 723
killerbarney Avatar asked Aug 18 '10 15:08

killerbarney


People also ask

What is inclusion tag in Django?

The Django developer can define the custom template tag and filter to the extent the template engine and the new template tag can be used using the {% custom_tag %}. The template tag that is used to display data by rendering another template is called the inclusion tag.

Can I use filter () in Django template?

Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.

How do I register a tag in Django?

Registering the tagThe tag() method takes two arguments: The name of the template tag – a string. If this is left out, the name of the compilation function will be used. The compilation function – a Python function (not the name of the function as a string).


2 Answers

This sounds like a job for the render_to_string or render_to_response shortcuts:
https://docs.djangoproject.com/en/dev/ref/templates/api/#the-render-to-string-shortcut
https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#django.shortcuts.render_to_response

We can still use the inclusion tag to generate a template context dict from our args (as helpfully pointed out by @BobStein-VisiBone in comments)

from django.template.loader import render_to_string
from django.shortcuts import render_to_response

from .templatetags import my_inclusion_tag


rendered = render_to_string('my_include.html', my_inclusion_tag(foo='bar'))

#or

def my_view(request):
    if request.is_ajax():
        return render_to_response('my_include.html',
                      my_inclusion_tag(foo='bar'),
                      context_instance=RequestContext(request))
like image 141
Anentropic Avatar answered Oct 25 '22 20:10

Anentropic


quick and dirty way could be to have a view, that renders a template, that only contains your templatetag.

like image 32
sjh Avatar answered Oct 25 '22 19:10

sjh