Thierry Lam
Thierry Lam

Reputation: 46284

How do include a dynamic template from another app in Django?

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?

Upvotes: 1

Views: 3500

Answers (3)

googletorp
googletorp

Reputation: 33275

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.

Upvotes: 0

Andre Miller
Andre Miller

Reputation: 15493

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})

Upvotes: 0

Dave Martorana
Dave Martorana

Reputation: 1331

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.

Upvotes: 2

Related Questions