Python 在模板中包含视图

Python 在模板中包含视图,python,django,Python,Django,在django中,我有一个填充模板html文件的视图,但在html模板中,我希望包含另一个使用不同html模板的视图,如下所示: {% block content %} Hey {{stuff}} {{stuff2}}! {{ view.that_other_function }} {% endblock content %} 这可能吗?是的,您需要使用模板标记来完成这项工作。如果只需呈现另一个模板,则可以使用包含标记,或者可能只使用内置的{%include'路径/to/template.

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

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

{{ view.that_other_function }}

{% endblock content %}

这可能吗?

是的,您需要使用模板标记来完成这项工作。如果只需呈现另一个模板,则可以使用包含标记,或者可能只使用内置的{%include'路径/to/template.html%}

模板标记可以执行Python中可以执行的任何操作

[跟进] 可以使用“渲染到字符串”方法:

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>
/my\u项目/
/我的应用程序/
__初始值
/模板标签/
__初始值
my_tags.py
#my_tags.py
从django导入模板
register=template.Library()
@register.inclusion_标记('other_template.html'))
def say_hello(takes_context=True):
返回{'name':'John'}
#其他_template.html
{%if request.user.is_anonymous%}
{#我们的inclusion标记接受一个上下文,它允许我们访问请求#}
你好,客人

{%else%} 你好,{{name}}

{%endif%} #main_template.html {%load my_tags%} 废话,废话,废话{%say_hello%}


inclusion标记呈现另一个模板,如您所需,但无需调用view函数。希望这能让你走。包含标签上的文档位于:

使用您的示例和您对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))

有人创建了一个模板标记。我试过了,效果不错。使用该模板标记的优点是,您不必重写现有视图。

如果使用内置的{%include'path/to/template.html'%},它不会只呈现模板吗?我想让它呈现\u到\u响应,填写template.html,然后包含它。我添加了一个后续答案。我不完全理解你的意思,我已经将render\u导入到\u字符串,但我不知道如何使用content=。。。行
def somepage(request):返回render_to_response(“templates/template1.html”,{“name”:“John Doe”},context_instance=RequestContext(request))
这就是我的视图的样子,我将如何合并您所说的内容?从注释中的代码中,您可以使用一个包含标记,它将字典传递给模板,并将模板的内容呈现到位。我已经编辑了我的答案以提供一个示例。不要忘记在创建第一个自定义模板标记后重新运行
python manage.py runserver