仅从视图中呈现HTML?

2024-04-26 15:00:25 发布

您现在位置:Python中文网/ 问答频道 /正文

当前render_to_response返回一个包含html的HttpResponse对象,但是有没有方法只从模板、字典和视图请求中呈现html?你知道吗

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

即:

你知道吗菜单.html地址:

<div>menu {{ text }}</div>

我想要这个:

你知道吗模板.html地址:

<div >...{{ menu }} </div>

查看

def menu(request, ...):
    # do menu variable calculations here
    # returned html string rendered from template, request, kwargs, and variables    

def base(request, ...):
    menu = menu(request, ...) # rendered html for menu values
    render_to_response("template.html", context={"menu":menu})

而不是:

你知道吗模板.html你知道吗

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

查看

def base(request, ...):
    # calculate menu variable values here
    render_to_response("template.html", context=dictionary_of_menu_items)

Tags: todiv视图模板hereresponserequest地址
2条回答

当然有:render_to_response是一个快捷方式,您可以直接在模板上调用render。这在tutorial中有描述。你知道吗

template = loader.get_template('template.html')
context = Context(dictionary_of_items)
rendered = template.render(context)

但是,对于您的用例,我认为inclusion tags可能更适合。你知道吗

我想您可以使用django.template.loader.render_to_string生成您的“菜单”html。这将返回一个包含已计算HTML的字符串。你知道吗

然后,在template.html中,在计算menu模板变量时,应该使用safe过滤器。你知道吗

<div>{{menu|safe}}</div>

相关问题 更多 >