在模板中包含视图

时间:2011-05-04 04:48:10

标签: python django

在django中我有一个视图填写模板html文件,但在html模板中我想要包含另一个使用不同html模板的视图,如下所示:

{% block content %}
Hey {{stuff}} {{stuff2}}!

{{ view.that_other_function }}

{% endblock content %}

这可能吗?

3 个答案:

答案 0 :(得分:6)

是的,你需要使用模板标签来做到这一点。如果你需要做的只是渲染另一个模板,你可以使用包含标记,或者可能只使用内置的{%include'path / to / template.html'%}

模板标签可以做任何你在Python中可以做的事情。

http://docs.djangoproject.com/en/1.3/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>

包含标记会像您需要的那样呈现另一个模板,但无需调用视图函数。希望能让你前进。关于包含标签的文档位于:http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#inclusion-tags

答案 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))

答案 2 :(得分:1)

有人创建了loads a view的模板标记。我试过了,它确实有效。使用该模板标记的优点是您不必重写现有视图。

相关问题