在django我有一个视图,填写模板html文件,但在html模板内我想包含另一个使用不同的html模板的视图,如下所示:
{% block content %}
Hey {{stuff}} {{stuff2}}!
{{ view.that_other_function }}
{% endblock content %}
Run Code Online (Sandbox Code Playgroud)
这可能吗?
是的,您需要使用模板标记来执行此操作.如果你需要做的只是渲染另一个模板,你可以使用包含标记,或者可能只使用内置的{%include'path/to/template.html'%}
模板标签可以执行您在Python中可以执行的任何操作.
http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/
[Followup]您可以使用render_to_string方法:
from django.template.loader import render_to_string
content = render_to_string(template_name, dictionary, context_instance)
Run Code Online (Sandbox Code Playgroud)
您需要从上下文中解析请求对象,或者如果需要利用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>
Run Code Online (Sandbox Code Playgroud)
包含标记会像您需要的那样呈现另一个模板,但无需调用视图函数.希望能让你前进.关于包含标签的文档位于:http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#inclusion-tags