2024-04-30 01:07:12 发布
网友
这是一个相当基本的问题(我是Django的新手),但在模板中使用视图中的变量集时遇到了问题。如果我在视图中初始化一个字符串或列表(即h=“hello”),然后尝试在模板中调用它:{{ h }} 既没有输出也没有错误。类似地,如果我尝试在模板中使用不存在的变量:
{{ h }}
{{ asdfdsadf }}
再次没有错误报告。这正常吗?以及如何在模板中使用变量。谢谢!
是的!这很正常。模板中的此类错误会自动失败,这在Django中是意料之中的。
要正确呈现模板,请使用render_to_response('your_template.html', {'h':h})(如果上下文字典很大,还有一个讨厌的快捷方式render_to_response('your_template.html', locals()))
render_to_response('your_template.html', {'h':h})
render_to_response('your_template.html', locals())
下面是一些示例说明:http://www.djangobook.com/en/beta/chapter04/(关于如何处理无效变量的部分)
你也可以使用
return render(request, 'your_template.html', {'h':h, 'var1':var1})
请参阅有关https://docs.djangoproject.com/es/1.9/topics/http/shortcuts/的最新手册
要访问模板中的变量,它必须位于用于呈现该模板的上下文中。我猜在呈现模板时,不会将上下文字典传递给模板。
http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render-to-response
引用的“dictionary”有一个dictionary,它包含您希望在上下文中有可用的所有变量。例如:
return render_to_response('your_template.html', {'h': h})
至于“没有错误”的错误。。。这是无效模板变量的默认设置。如果愿意,可以在项目的设置中更改此设置。
http://docs.djangoproject.com/en/dev/ref/settings/#template-string-if-invalid
是的!这很正常。模板中的此类错误会自动失败,这在Django中是意料之中的。
要正确呈现模板,请使用
render_to_response('your_template.html', {'h':h})
(如果上下文字典很大,还有一个讨厌的快捷方式render_to_response('your_template.html', locals())
)下面是一些示例说明:http://www.djangobook.com/en/beta/chapter04/(关于如何处理无效变量的部分)
你也可以使用
请参阅有关https://docs.djangoproject.com/es/1.9/topics/http/shortcuts/的最新手册
要访问模板中的变量,它必须位于用于呈现该模板的上下文中。我猜在呈现模板时,不会将上下文字典传递给模板。
http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render-to-response
引用的“dictionary”有一个dictionary,它包含您希望在上下文中有可用的所有变量。例如:
至于“没有错误”的错误。。。这是无效模板变量的默认设置。如果愿意,可以在项目的设置中更改此设置。
http://docs.djangoproject.com/en/dev/ref/settings/#template-string-if-invalid
相关问题 更多 >
编程相关推荐