在模板中使用Django视图变量 [英] Using Django view variables inside templates
问题描述
这是一个相当基本的问题(我是Django的新手),但是在模板中的视图中使用变量集时遇到了麻烦。如果我在视图中初始化字符串或列表(即h = hello),然后尝试在模板中调用它:
{{h}}
既没有输出也没有错误。同样,如果我尝试在模板中使用不存在的变量:
this is a rather basic question (I'm new to Django) but I'm having trouble using a variable set in my view inside my template. If I initialize a string or list inside my view (i.e. h = "hello") and then attempt to call it inside a template:
{{ h }}
there is neither output nor errors. Similarly, if I try to use a variable inside my template that doesn't exist:
{{ asdfdsadf }}
再次没有错误报告。这正常吗?以及如何在模板中使用变量。谢谢!
there is again no error reported. Is this normal? And how can I use my variables within my templates. Thanks!
推荐答案
为了访问模板中的变量,它必须位于用于渲染的上下文中该模板。我的猜测是,渲染模板时不会将上下文字典传递给模板。
In order to have access to a variable in a template, it needs to be in the the context used to render that template. My guess is you aren't passing a context dictionary to the template when you render it.
http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render-to-response
引用的词典中有一个字典,其中包含您要在上下文中使用的所有变量。例如:
The "dictionary" referenced there is a dictionary that contains all the variables you want to have available in the context. For example:
return render_to_response('your_template.html', {'h': h})
就没有错误错误而言……这是无效模板变量的默认设置。您可以根据需要在项目设置中进行更改。
As far as the "no error" error goes... That's the default setting for an invalid template variable. You can change that in the project's settings if you'd like.
http://docs.djangoproject.com/en/dev/ref/settings/#template-string-if-invalid
这篇关于在模板中使用Django视图变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!