所以,我應該讓這些形象的名字我的views.py文件中,並通過 名稱(zoo_alligator)到上下文要由 模板以後檢索?這是否是正確的方法?
當然,這是一個辦法。事情是這樣的:
(r'show/(?P<in_path>.*)$','someapp.image_view')
然後在image_view
:
def image_view(request,in_path):
img = in_path.replace('/','_')+'.jpg'
return render(request,'some_template.html',{'path':img})
然而,隨着你的觀點很簡單 - 你可以直接從urls.py
傳遞路徑模板,使用direct_to_template
:
from django.views.generic.simple import direct_to_template
(r'show/(?P<in_path>.*)$',direct_to_template,{'template':'some_template.html'})
In some_template.html
:
<img src="{{ params.in_path }}">
問題是,由於默認篩選器沒有「替換」功能,因此您不會完成字符串格式設置。您可以輕鬆地編寫自定義過濾器:
@register.filter
@stringfilter
def format_path(the_path):
return the_path.replace('/','_')+'.jpg'
然後修改模板:
<img src="{{ params.in_path|format_path }}">
你應該閱讀文檔上writing custom filters and tags的更多細節,包括在哪裏存儲過濾代碼,以確保使Django能夠找到它。
Kalid我通過獲取URL並使用它的名稱來動態獲取每個圖像,從而找到了解決方法。 但可悲。我無法得到它加載只是正常的靜態文件,而不是動態獲取.. :( 我不斷收到'無效塊標記:'靜態',預計'endblock''錯誤...仍然沒有' t能夠找出我的問題所在 – user805981
您在模板頂部缺少'{%load static%}' –
當我擴展了base.html時,它已經在那裏了,我真的需要它嗎?再次? – user805981