问题描述
在django中,我有一个观点,填写一个模板html文件,但是在html模板内部我想包含另一个使用不同的html模板的视图:
In django I have a view that fills in a template html file but inside the html template I want to include another view that uses a different html template like so:
{% block content %}
Hey {{stuff}} {{stuff2}}!
{{ view.that_other_function }}
{% endblock content %}
这是可能吗?
推荐答案
是的,你需要使用模板标签来做到这一点。如果您需要做的只是渲染另一个模板,则可以使用包含标记,或者可能只是内置{%include'path / to / template.html'%}
Yes, you need to use a template tag to do that. If all you need to do is render another template, you can use an inclusion tag, or possibly just the built in {% include 'path/to/template.html' %}
模板标签可以在Python中做任何事情。
Template tags can do anything you can do in Python.
[Followup]
您可以使用render_to_string方法:
[Followup]You can use the render_to_string method:
from django.template.loader import render_to_string
content = render_to_string(template_name, dictionary, context_instance)
您需要解决请求对象从上下文中,或者如果需要使用context_instance,则将其作为参数传递给模板标签。
You'll either need to resolve the request object from the context, or hand it in as an argument to your template tag if you need to leverage the context_instance.
跟进答案:包含标签示例
Followup Answer: Inclusion tag example
Django希望模板标签生活在名为templatetags的文件夹中,该文件夹位于应用程序模块这是你安装的应用程序...
Django expects template tags to live in a folder called 'templatetags' that is in an app module that is in your installed apps...
/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>
包含标记根据需要呈现另一个模板,但无需调用视图功能。希望能让你走。关于包含标签的文档位于:
The inclusion tag renders another template, like you need, but without having to call a view function. Hope that gets you going. The docs on inclusion tags are at: http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#inclusion-tags
这篇关于在模板中添加视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!