Django Template Tags in Views

前端 未结 4 1457
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 12:47

Hi I need to refresh my custom template tag --right_side.py-- via Ajax. Is there a way to import the template tag in the view and return it as HttpResponse because I don\'t

相关标签:
4条回答
  • 2020-12-29 13:02

    I found this solution :

    from templatetags_file_name import my_templatetag
    return render (request,'path/to/template.html', my_templatetag(parameter) )
    

    And, in my "templatetags_file_name", "my_templatetag" is like that :

    @register.inclusion_tag('path/to/template.html') 
    def my_templatetag(parameter):
        #my operations
        return locals()
    
    0 讨论(0)
  • 2020-12-29 13:13

    I had this same question awhile ago, I was loading HTML snippets with AJAX which I had already written as template tags. And I was trying to avoid duplicating the code in two places.

    This is what I came up with to render a template tag from a view (called via ajax):

    from django.template import RequestContext, Template
    
    def myview(req):
       context = RequestContext({'somearg':"FooBarBaz"})
    
       template_string = """
          {% load my_tag from tagsandfilters %}
          {% my_tag somearg %}
       """
    
       t = Template(template_string)
       return HttpResponse(t.render(context))
    
    0 讨论(0)
  • 2020-12-29 13:16

    You could create a template just containing your templatetag and nothing else. Then you would have in right_side.html:

    {%load cems_templatetags%}
    {%right_side%}
    

    and in the view something like:

    if request.isAjax():
      return render_to_response('right_side.html',RequestContext(request))
    
    0 讨论(0)
  • 2020-12-29 13:20

    I find it really useful when refreshing an area with ajax. So thought it would be good to share it:

    First you import the custom template tag you coded in your view file.

    from your_app_name.templatetags import your_tag_name 
    

    And then you use it like this:

    return HttpResponse(your_tag_name.your_method(context))
    

    That worked for me and I got the template tag as response from server and refreshed the div with that result.

    0 讨论(0)
提交回复
热议问题