2011-03-18 72 views
11

的URL的第一部分,我用request.path獲取當前的URL。例如,如果當前URL爲「/測試/富/巴茲」我想知道,如果它與一個字符串序列開始,讓我們說/測試。如果我嘗試使用:獲得Django的模板

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

我得到一個錯誤說,它無法解析表達式的剩餘部分:

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。

回答

3

你不能按照設計,調用函數與Django模板參數。

一個簡單的方法是把你在你的要求範圍內所需要的狀態,就像這樣:

def index(request): 
    c = {'is_test' : request.path.startswith('/test')} 
    return render_to_response('index.html', c, context_instance=RequestContext(request)) 

然後,你將有一個is_test變量,你可以在你的模板中使用:

{% if is_test %} 
    Test 
{% endif %} 

這種方法也有抽象的確切路徑測試(「/測試」),你的模板,它可能是有幫助的優勢。

0

從哲學節在this page of Django docs

模板系統不會執行 任意Python表達式

你真的應該寫一個自定義標籤或傳遞一個變量,告知如果模板路徑始於'/test'

55

您可以使用切片過濾器來獲取網址的第一部分

{% if request.path|slice:":5" == '/test' %} 
    Test 
{% endif %} 

現在不能試試這個,不知道如果過濾器在裏面工作「如果」的標籤, 如果不工作,你可以使用「與」標籤

{% with request.path|slice:":5" as path %} 
    {% if path == '/test' %} 
    Test 
    {% endif %} 
{% endwith %} 
+0

我得到'if'語句格式錯誤。 – Seitaridis 2011-03-21 15:02:24

+2

其對我的工作很好 – Ted 2012-01-17 09:00:50

+0

您的第一個解決方案正常工作! :) – 2014-08-10 18:13:16

22

不是檢查的與startswith前綴,您可以通過內置的in標籤入會檢查得到同樣的事情。

{% if '/test' in request.path %} 
    Test 
{% endif %} 

這將傳遞情況下字符串不是嚴格的開始,但你可以簡單地避免這些類型的網址。

+0

這就是我想要的。謝謝!這裏絕對是最好的答案。 – 2014-07-31 15:26:40

+6

如果我們需要查找我們是否在某個網站的某個部分,某些情況下無法使用。例如,我們需要找到我們在「課程」部分。 '/ courses/1 /' - OK,'/ login /?next =/courses/1 /' - 不行。 – Marboni 2015-02-17 18:39:12

0

我使用上下文處理器在這樣的情況下:

*。與創建文件的核心/ context_processors.py:

def variables(request): 
     url_parts = request.path.split('/') 
     return { 
      'url_part_1': url_parts[1], 
     } 

*。在settings.py

'core.context_processors.variables', 

到模板「context_processors名單:添加記錄。

*。在任何模板使用

{{ url_part_1 }}