【发布时间】:2011-08-18 05:35:22
【问题描述】:
在 django 中,我有一个填充模板 html 文件的视图,但在 html 模板中我想包含另一个使用不同 html 模板的视图,如下所示:
{% block content %}
Hey {{stuff}} {{stuff2}}!
{{ view.that_other_function }}
{% endblock content %}
这可能吗?
【问题讨论】:
在 django 中,我有一个填充模板 html 文件的视图,但在 html 模板中我想包含另一个使用不同 html 模板的视图,如下所示:
{% block content %}
Hey {{stuff}} {{stuff2}}!
{{ view.that_other_function }}
{% endblock content %}
这可能吗?
【问题讨论】:
是的,您需要使用模板标签来执行此操作。如果你需要做的只是渲染另一个模板,你可以使用包含标签,或者可能只是内置的 {% include 'path/to/template.html' %}
模板标签可以做任何你可以在 Python 中做的事情。
https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/
[跟进] 你可以使用 render_to_string 方法:
from django.template.loader import render_to_string
content = render_to_string(template_name, dictionary, context_instance)
如果您需要利用 context_instance,您需要从上下文中解析请求对象,或者将其作为参数传递给您的模板标签。
后续回答:包含标记示例
Django 期望模板标签存在于名为“templatetags”的文件夹中,该文件夹位于已安装应用程序中的应用程序模块中...
/my_project/
/my_app/
__init__.py
/templatetags/
__init__.py
my_tags.py
#my_tags.py
from django import template
register = template.Library()
@register.inclusion_tag('other_template.html')
def say_hello(takes_context=True):
return {'name' : 'John'}
#other_template.html
{% 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 %}
#main_template.html
{% load my_tags %}
<p>Blah, blah, blah {% say_hello %}</p>
包含标签呈现另一个模板,就像您需要的那样,但无需调用视图函数。希望这能让你继续前进。包含标签的文档位于:https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/#inclusion-tags
【讨论】:
def somepage(request): return render_to_response("templates/template1.html", {"name":"John Doe"},context_instance=RequestContext(request)) 这是我的视图,我将如何融入您所说的内容?
python manage.py runserver :)
使用你的例子和你对 Brandon 的回答的回答,这应该对你有用:
模板.html
{% block content %}
Hey {{stuff}} {{stuff2}}!
{{ other_content }}
{% endblock content %}
views.py
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))
【讨论】:
有人创建了loads a view 的模板标签。我已经尝试过了,它有效。使用该模板标签的好处是您不必重写现有视图。
【讨论】: