那么,我是否应该在我的 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'})
在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 }}">
您应该阅读有关编写自定义过滤器和标签的文档以获取更多详细信息,包括存储过滤器代码的位置以确保 django 可以找到它。