从Django模板获取URL的第一部分 [英] Obtain the first part of an URL from Django template

查看:130
本文介绍了从Django模板获取URL的第一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use request.path to obtain the current URL. For example if the current URL is "/test/foo/baz" I want to know if it starts with a string sequence, let's say /test. If I try to use:

{% if request.path.startswith('/test') %}
    Test
{% endif %} 

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

I get an error saying that it could not parse the remainder of the expression:

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

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

One solution would be to create a custom tag to do the job. Is there something else existing to solve my problem? The Django version used is 1.0.4.

推荐答案

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

You can not pass arguments to normal python functions from within a django template. To solve you problem you will need a custom template tag: http://djangosnippets.org/snippets/806/

这篇关于从Django模板获取URL的第一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆