在模板中包含视图
在Django中,我有一个视图,它会填充一个模板的HTML文件。但是在这个HTML模板里面,我想要包含另一个视图,这个视图使用的是不同的HTML模板,像这样:
{% block content %}
Hey {{stuff}} {{stuff2}}!
{{ view.that_other_function }}
{% endblock content %}
这样做可以吗?
3 个回答
1
有人创建了一个模板标签,可以用来加载一个视图。我试过了,确实有效。使用这个模板标签的好处是,你不需要重新编写已经存在的视图。
2
根据你的例子和你对Brandon回答的解释,这样做应该对你有帮助:
模板文件:template.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))
10
是的,你需要使用一个模板标签来实现这个功能。如果你只是想渲染另一个模板,可以使用一个包含标签,或者直接使用内置的 {% 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)
如果你需要使用上下文实例,你要么需要从上下文中获取请求对象,要么将其作为参数传递给你的模板标签。
后续回答:包含标签示例
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