Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 仅从视图中呈现HTML?_Python_Django - Fatal编程技术网

Python 仅从视图中呈现HTML?

Python 仅从视图中呈现HTML?,python,django,Python,Django,当前render_to_响应返回一个包含html的HttpResponse对象,但是是否有方法仅从模板、字典和视图请求中呈现html 注意:我之所以要这样做,是因为我可以将django视图嵌套在另一个视图中,并以这种方式包含它们的值,而不是通过模板包含 i、 e: menu.html: <div>menu {{ text }}</div> 而不是: template.html <div>{% include menu.html %}</div>

当前render_to_响应返回一个包含html的HttpResponse对象,但是是否有方法仅从模板、字典和视图请求中呈现html

注意:我之所以要这样做,是因为我可以将django视图嵌套在另一个视图中,并以这种方式包含它们的值,而不是通过模板包含

i、 e:

menu.html:

<div>menu {{ text }}</div>
而不是:

template.html

<div>{% include menu.html %}</div>

当然有:
render\u to\u response
是一种快捷方式,您可以随时直接在模板上调用render。除其他地方外,在中介绍了这一点

template = loader.get_template('template.html')
context = Context(dictionary_of_items)
rendered = template.render(context)
但是,对于您的用例,我认为可能更适合。

我想您可以使用生成“菜单”html。这将返回一个带有已计算HTML的字符串

然后,在
template.html
中,在计算
菜单
模板变量时,应使用
safe
过滤器

<div>{{menu|safe}}</div>
{{菜单|安全}

包含标记是否与常规变量模板一样有效?效率没有差别,它们的工作方式相同。
def base(request, ...):
    # calculate menu variable values here
    render_to_response("template.html", context=dictionary_of_menu_items)
template = loader.get_template('template.html')
context = Context(dictionary_of_items)
rendered = template.render(context)
<div>{{menu|safe}}</div>