[Solved]-Include a view in a template


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.


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…


from django import template

register = template.Library()

def say_hello(takes_context=True):
    return {'name' : 'John'}

{% 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 %}

{% 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:


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

{{ other_content }}

{% endblock content %}


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.

Leave a comment