【问题标题】:Django - Would I be able to use template tags for rendering HTML given URL path conditionals?Django - 我可以使用模板标签来呈现给定 URL 路径条件的 HTML 吗?
【发布时间】:2021-10-11 17:39:12
【问题描述】:

我有一个路径为/articles/ 的博客页面。我想使用条件语句来反映 HTML 呈现。

例如,我的博客使用分页器来发布博客文章。分页器使用 URL 查询来检索帖子对象的下一页,如下所示:/articles/?page=2

我希望下一页以不同的方式对 HTML 模板进行样式化,因此我使用条件语句的理由。

这是我使用的模板:

{% if request.path == '/articles/' %}
# Render HTML only meant for the above path



{% elif request.path != '/articles/'%} 
# Render HTML for paths that are NOT the exact match above, such as pagination URLs, 
# search querys, categories filtering, etc...

{% endif %}

我当前的错误是我只呈现第一条语句:if request.path == '/articles/' 用于所有内容,甚至是非精确匹配。

所以这个 URL 路径:/articles/?page=2 正在呈现:{% if request.path == '/articles/' %},由于不等号,它应该呈现 elif {% elif request.path != '/articles/'%}

以上是否可能仅与 HTML 模板标签有关?我知道我可以使用 urls.py 和编辑视图,但我使用的是 wagtail CMS,并且使用模板似乎是现在最容易做的事情。

【问题讨论】:

标签: python django django-templates wagtail


【解决方案1】:

request.pathdoes not include the '?...' querystring part of the URL,所以这是按设计工作的 - URL /articles/?page=2 的路径部分 /articles/

Django 将查询字符串编译成字典request.GET,因此一种方法是检查该字典是否为空:

{% if not request.GET %}
    request is for the plain URL /articles/
{% else %}
    request has a querystring parameter on it
{% endif %}

【讨论】:

  • 太棒了,非常感谢,这是一种聪明的做法。我唯一担心的是条件似乎很宽泛。有什么需要担心的警告吗?
  • 它似乎并不适用于所有情况,例如,这个查询:/articles/tag/model/,所以我最终使用了 Mohammad 评论给出的第一个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
相关资源
最近更新 更多