Include a view in a template

后端 未结 3 1101
感情败类
感情败类 2021-02-20 09:15

In django I have a view that fills in a template html file but inside the html template I want to include another view that uses a different html template like so:



        
3条回答
  •  礼貌的吻别
    2021-02-20 09:49

    Yes, you need to use a template tag to do that. If all you need to do is render another template, you can use an inclusion tag, or possibly just the built in {% include 'path/to/template.html' %}

    Template tags can do anything you can do in Python.

    https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/

    [Followup] You can use the render_to_string method:

    from django.template.loader import render_to_string
    content = render_to_string(template_name, dictionary, context_instance)
    

    You'll either need to resolve the request object from the context, or hand it in as an argument to your template tag if you need to leverage the context_instance.

    Followup Answer: Inclusion tag example

    Django expects template tags to live in a folder called 'templatetags' that is in an app module that is in your installed apps...

    /my_project/
        /my_app/
            __init__.py
            /templatetags/
                __init__.py
                my_tags.py
    
    #my_tags.py
    from django import template
    
    register = template.Library()
    
    @register.inclusion_tag('other_template.html')
    def say_hello(takes_context=True):
        return {'name' : 'John'}
    
    #other_template.html
    {% if request.user.is_anonymous %}
    {# Our inclusion tag accepts a context, which gives us access to the request #}
        

    Hello, Guest.

    {% else %}

    Hello, {{ name }}.

    {% endif %} #main_template.html {% load my_tags %}

    Blah, blah, blah {% say_hello %}

    The inclusion tag renders another template, like you need, but without having to call a view function. Hope that gets you going. The docs on inclusion tags are at: https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/#inclusion-tags

提交回复
热议问题