Django Template Tags in Views

前端 未结 4 1458
被撕碎了的回忆
被撕碎了的回忆 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: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))
    

提交回复
热议问题