python - 模板内的 Django Cookie 值

标签 python django cookies

如果请求中存在某个指定的 cookie,我想在布局中显示其他链接。我已设法访问模板内的“请求”变量。我做了以下事情:

 {% if request.COOKIES.['cookie_name'] %}
   <li><a href="{% url 'felhasznalo:felhasznalo-detail' %}">some link</a></li>
 {% endif  %}

但它会抛出此错误:TemplateSyntaxError at/ 无法解析剩余部分:'request.COOKIES.['cookie_name']'中的'['cookie_name']'

我做错了什么? (cookie存在,如果我打印出request.COOKIES,它会写出所有包含cookie的名称及其值)

最佳答案

https://docs.djangoproject.com/en/1.11/ref/templates/api/#variables-and-lookups

使用

{% if request.COOKIES.cookie_name %}
   <li><a href="{% url 'felhasznalo:felhasznalo-detail' %}">some link</a></li>
{% endif  %}

Variables and lookups

Variable names must consist of any letter (A-Z), any digit (0-9), an underscore (but they must not start with an underscore) or a dot.

Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

Dictionary lookup. Example: foo["bar"]
Attribute lookup. Example: foo.bar
List-index lookup. Example: foo[bar]

关于python - 模板内的 Django Cookie 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34463979/

相关文章:

Django:在没有端口的服务器上运行 Django 应用程序?

python - 如何在 Pylons 中使用重定向设置 cookie

ios - Cookie 不适用于 Apple 设备上的 WebSocket

javascript - 我如何/我可以通过 javascript 访问 sessionid cookie?

python - 使用 python 的 bs4 的 HTML 选择器

python - 有没有办法根据 pandas DataFrame 中的类别查找模式?

Python——sympysolve()返回另一个方程而不是值

python - 在 CPanel 中使用 Python 在 Django 管理面板中加载静态文件

python - 如何读取具有多个 header block 的数据

python - 如何在 django-allauth 社交帐户注册流程中显示自定义表单