在 Django 模板中实现正则表达式

Rob*_*bin 1 regex django django-templates

我通过检查 url 是否与当前 url 匹配来使页面导航处于活动状态。

<li>
  {% url 'blog' as blog_url %}
  <a href="{{blog_url}}" {% if request.get_full_path == blog_url %}class="active"{% endif %}>Blog</a>
</li>
Run Code Online (Sandbox Code Playgroud)

现在我正在使用分页,当转到不同的页面时会导致 url 如下所示:

/blog/

/blog/?page=2
/blog/?page=3
Run Code Online (Sandbox Code Playgroud)

而上面的代码不起作用。那么无论如何要在模板中使用正则表达式来获取任何东西(如/blog/*)并使其处于活动状态。非常感谢您的帮助和指导。谢谢你。

don*_*yor 5

你可以做

{% if '/blog/' in request.path %}class="active"{% endif %}
Run Code Online (Sandbox Code Playgroud)

不需要正则表达式