从Django模板获取URL的第一部分

Sei*_*dis 14 python django url templates django-templates

request.path用来获取当前的URL.例如,如果当前URL是"/ test/foo/baz",我想知道它是否以字符串序列开头,让我们说/ test.如果我尝试使用:

{% if request.path.startswith('/test') %}
    Test
{% endif %} 
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,说它无法解析表达式的其余部分:

Could not parse the remainder: '('/test')' from 'request.path.startswith('/test')'
Request Method: GET
Request URL:    http://localhost:8021/test/foo/baz/
Exception Type: TemplateSyntaxError
Exception Value:    
Could not parse the remainder: '('/test')' from 'request.path.startswith('/test')'
Exception Location: C:\Python25\lib\site-packages\django\template\__init__.py in   __init__, line 528
Python Executable:  C:\Python25\python.exe
Python Version: 2.5.4
Template error
Run Code Online (Sandbox Code Playgroud)

一种解决方案是创建自定义标签来完成工作.还有其他东西可以解决我的问题吗?使用的Django版本是1.0.4.

Fer*_*ran 60

您可以使用切片过滤器来获取网址的第一部分

{% if request.path|slice:":5" == '/test' %}
    Test
{% endif %} 
Run Code Online (Sandbox Code Playgroud)

现在无法尝试,也不知道过滤器是否在'if'标签内工作,如果不起作用则可以使用'with'标签

{% with request.path|slice:":5" as path %}
  {% if path == '/test' %}
    Test
  {% endif %} 
{% endwith %} 
Run Code Online (Sandbox Code Playgroud)


The*_*One 27

您可以通过检查内置in标记的成员资格来获取相同的内容,而不是使用startswith检查前缀.

{% if '/test' in request.path %}
    Test
{% endif %} 
Run Code Online (Sandbox Code Playgroud)

这将传递字符串不严格在开头的情况,但您可以简单地避免使用这些类型的URL.

  • 如果我们需要查找我们是否在某个网站的某个部分,则在某些情况下无效.例如,我们需要找到我们在"课程"部分.`/ courses/1 /` - 好的,`/ login /?next =/courses/1 /` - 不行. (6认同)

Ber*_*ant 5

您不能从django模板中将参数传递给普通的python函数.要解决您的问题,您需要一个自定义模板标记:http://djangosnippets.org/snippets/806/