在模板中使用 Django 视图变量 [英] Using Django view variables inside templates

查看:33
本文介绍了在模板中使用 Django 视图变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当基本的问题(我是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆