【问题标题】:access args in render function in django在 django 的渲染函数中访问 args
【发布时间】:2017-11-04 06:10:56
【问题描述】:

我正在使用 Django,无法访问我通过渲染方法传递的参数 (args)。我收到错误:/app/ 处的 TemplateSyntaxError。 无法解析剩余部分:'['messages']' from 'args['messages']'

观看次数:

def index(request):
messages = ["This is message1", "This is message2"]
args = {'messages': messages}

return render(request, 'app/index.html', args)

索引html文件:

{% for message in args['messages'] %}

<div class="live_message">
    <p>{{ message }}</p>
</div>
{% endfor %}

出了什么问题,我该如何解决?

【问题讨论】:

    标签: python django render


    【解决方案1】:

    你称之为“args”的东西,Django 称之为“上下文”。

    您不需要将上下文项称为字典键。因此,像这样改写你的模板标签应该是让它工作所需的全部内容:

    {% for message in messages %}

    【讨论】:

    • 好吧,我该死的,它确实奏效了。为什么它会起作用? Django 是否将字典转换为渲染函数中的多个列表?我会在几分钟后接受你的回答。
    • 模板标签是一种语言抽象,看起来像 Python,但不遵循它的所有约定,所以像字典访问这样的东西不会像你期望的那样工作。上下文中的顶级键值对(“args”)仅由键引用。开发文档值得一读,这样你就知道在渲染过程中你能做什么和不能做什么:docs.djangoproject.com/en/dev/ref/templates/builtins
    猜你喜欢
    • 2023-04-04
    • 2018-01-08
    • 2018-11-24
    • 2018-09-23
    • 2021-09-12
    • 2020-12-21
    • 2018-04-05
    相关资源
    最近更新 更多