开发者

Include a view in a template

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:

{% block content %}
Hey {{stuff}} {{stuff2}}!

{{ view.that_other_function }}

{% endblock c开发者_StackOverflowontent %}

Is this possible?


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 #}
    <p>Hello, Guest.</p>
{% else %}
    <p>Hello, {{ name }}.</p>
{% endif %}

#main_template.html
{% load my_tags %}
<p>Blah, blah, blah {% say_hello %}</p>

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


Using your example and your answer to Brandon's response, this should work for you then:

template.html

{% block content %}
Hey {{stuff}} {{stuff2}}!

{{ other_content }}

{% endblock content %}

views.py

from django.http import HttpResponse
from django.template import Context, loader
from django.template.loader import render_to_string


def somepage(request): 
    other_content = render_to_string("templates/template1.html", {"name":"John Doe"})
    t = loader.get_template('templates/template.html')
    c = Context({
        'stuff': 'you',
        'stuff2': 'the rocksteady crew',
        'other_content': other_content,
    })
    return HttpResponse(t.render(c))


Someone created a template tag that loads a view. I've tried it, and it works. The advantage of using that template tag is that you don't have to rewrite your existing views.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜