在django模板中获取模板语法错误 [英] getting template syntax error in django template

查看:115
本文介绍了在django模板中获取模板语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码视图:

  tracks = client.get('/ tracks',order ='hotness' = 4)
artwork_url = []
轨道轨道:
artwork_url.append(str(track.artwork_url).replace(large,t300x300))


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

in .html

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

错误:

 异常类型:TemplateSyntaxError 
异常值:无法解析余数:'[forloop.counter]'from'artwork_url [forloop.counter]'


解决方案

由于您的 artwork_url 是一个列表,合理的方法是这样访问它:



artwork_url.forloop.counter



但它不会工作。 Django模板语言不是不幸的是



你应该这样访问。

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

但是这要求曲目是可变的,需要你在后端更改它。



所以如果你无法修改曲目,你必须实现一个这样的自定义模板过滤器



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



一个非常小而简单formatter:

  @ register.filter(name ='myDate')
def myFormatter(value,arg):
如果arg =='t300':
arg ='t300x300'
return str(value).replace(large,arg)
/ pre>

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]'

解决方案

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)

这篇关于在django模板中获取模板语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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