getting template syntax error in django template

别等时光非礼了梦想. 提交于 2019-12-10 12:18:18

问题


my code in view :

tracks = client.get('/tracks', order='hotness', limit=4)   
artwork_url=[]
for track in tracks:
    artwork_url.append(str(track.artwork_url).replace("large", "t300x300"))        


val={"tracks":tracks,"artwork_url":artwork_url}    
return render_to_response('music/tracks.html',val)

in .html

{% for track in tracks %} 
<li>
    <div class="genre-image">
        <img src="{{   artwork_url[forloop.counter] }}">
    </div>
{% endfor %} 

Error:

Exception Type: TemplateSyntaxError 
Exception Value:  Could not parse the remainder: '[forloop.counter]' from 'artwork_url[forloop.counter]'

回答1:


Since your artwork_url is a list, the reasonable way would be to access it like this:

artwork_url.forloop.counter

but it won't work. The Django template language isn't that advanced unfortunately.

You should access it like this.

{% for track in tracks %} 
<li><div class="genre-image">
<img src="{{ track.artwork_url }}">
</div>
{% endfor %}

But that requires that the tracks are mutable and require you to change it in the backend.

So if you're not able to modify the track you'd have to implement a custom template filter something like this

{{ track.artwork_url|myFormatter:'t300' }}

A very small and simple formatter:

@register.filter(name='myDate')
def myFormatter(value, arg):
    if arg == 't300':
        arg = 't300x300'
    return str(value).replace("large", arg)


来源:https://stackoverflow.com/questions/17258191/getting-template-syntax-error-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!