views:

415

answers:

3

I currently have two apps:

app1/
app2/
templates/
    app1.html
    app2.html

In app1.html, I'm including app2.html:

<!-- app1.html -->
{% include "app2.html" %}

app2 has some dynamic content:

<!-- app2.html -->
{% app2_value %}

When I display app1.html, the value app2_value doesn't show up. What's the best way to handle the above in Django?

+1  A: 

Django doesn't really process dynamic including like PHP or other languages do. Instead, you should have a base template, and use template inheritance and blocks to accomplish what you're trying to do.

So your app2.html would have the same dynamic content, but have a place for app1.html to either override or insert things.

app2.html:

{% block 'title' %}
{{ app2.title }}
{% endblock %}

{% block 'content' %}
{% endblock %}

App1's template can then extend App2's:

app1.html:

{% extends "app2.html" %}

{% block 'title' %}
Actually App 1!
{% endblock %}

{block 'content' %}
...
{% endblock %}

Unfortunately, include-handling is still new in Django and against best practices from what I've seen in the documentation and community.

Dave Martorana
I guess my intention was to make my apps re-usable by having include-handling. I'll probably have to handle that kind of logic on the view side since app2.html is supposed to be independent.
Thierry Lam
A: 

In Django your views and your templates are decoupled from each other, so when you use {% app2_value %} in a template it will assume that was passed to it from the calling view.

So, to answer your question, to get that value to display, pass it to app1 template in whatever view you use to call it:

# app1 views.py
from django.shortcuts import render_to_response
import app2

def app1_view(request):
    return render_to_response('app1.html', {'app2_value': app2.somevalue})
Andre Miller
A: 

You can actually render a temple as a string and then send it to another template to be displayed. You would still need to send the variabels to the template you are rending as a string. A good use case would be to use the same template to render list or dicts in a special way.

googletorp