如果请求中存在某个指定的 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/