StefanNch
StefanNch

Reputation: 2609

How do i render a template inside another template?

I'm new in Django and Python and I'm stuck! It's complicated to explain but I will give it a try... I have my index.html template with an include tag:

{% include 'menu.inc.html' %}

The menu is a dynamic (http://code.google.com/p/django-treemenus/). The menu-app holds a view that renders menu.inc.html:

from django.http import HttpResponse
from django.template import Context, loader
from treemenus.models import Menu

def mymenu(request):
    mainmenu = Menu.objects.get(id = 1)
    template = loader.get_template('menu.inc.html')
    context = Context({
        'mainmenu':mainmenu,
    })

    return HttpResponse(template.render(context))

So when I access index.html the server will serve it to me and django will load and serve menu.inc.html! But not the content! My question is:

  1. How do I reverse link the menu.inc.html to the view?! or
  2. How do I tell django that a template needs a rendered template by a specific view?!

I don't want put mainmenu = Menu.objects.get(id = 1) in my index's view because the menu will be on other pages too ... I was thinking iframes + rule in the urls.py, but that's an ugly workaround ...

Do I make any sense?!

Upvotes: 2

Views: 2573

Answers (1)

Manoj Govindan
Manoj Govindan

Reputation: 74675

At first blush this seems to be a case for adding an inclusion tag. You might want to write a custom tag that renders the tree menu. From the main view you can then pass the necessary context variables for this tag to work.

From the documentation:

Another common type of template tag is the type that displays some data by rendering another template.

Upvotes: 2

Related Questions