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

ぐ巨炮叔叔 提交于 2019-12-08 08:22:39

问题


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:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/1114622/how-do-include-a-dynamic-template-from-another-app-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!