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?
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.
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.
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).
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))
quick and dirty way could be to have a view, that renders a template, that only contains your templatetag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With