问题描述
我有一个模型字段,它存储一个URL列表(是的,我知道,这是错误的方式)为 url1\\\
。我需要将该字段分割成我的模板中的数组,所以我创建了自定义过滤器:
url2\\\
url3< ...>
@ register.filter ='split')
def split(value,arg):
return value.split(arg)
我以这种方式使用:
{%with game.screenshots | split:\\\
作为屏幕%}
{%屏幕中的屏幕%}
{{screen}}< br>
{%endfor%}
{%endwith%}
可以看到,拆分不想工作:我得到输出像 url1 url2 url3
(如果我看看源码,换行)。为什么?
Django有意遗漏了许多类型的模板标签,以阻止您在模板中进行太多的处理。 (不幸的是,人们通常只需自己添加这些类型的模板。)
这是一个完美的例子,它应该在你的模型中您的模板。
类游戏(models.Model):
...
def screenshots_as_list )
return self.screenshots.split('\\\
')
然后,在您的模板中,您只需执行以下操作:
{%for game.screenshots_as_list%}
{{screen} }<峰; br>
{%endfor%}
更清晰,更容易使用。 p>
I have a model field, which stores a list of URLs (yeah, I know, that's wrong way) as url1\nurl2\nurl3<...>
. I need to split the field into an array in my template, so I created the custom filter:
@register.filter(name='split')
def split(value, arg):
return value.split(arg)
I use it this way:
{% with game.screenshots|split:"\n" as screens %}
{% for screen in screens %}
{{ screen }}<br>
{% endfor %}
{% endwith %}
but as I can see, split doesn't want to work: I get output like url1 url2 url3
(with linebreaks if I look at the source). Why?
Django intentionally leaves out many types of templatetags to discourage you from doing too much processing in the template. (Unfortunately, people usually just add these types of templatetags themselves.)
This is a perfect example of something that should be in your model not your template.
class Game(models.Model):
...
def screenshots_as_list(self):
return self.screenshots.split('\n')
Then, in your template, you just do:
{% for screen in game.screenshots_as_list %}
{{ screen }}<br>
{% endfor %}
Much more clear and much easier to work with.
这篇关于Django模板 - 将字符串拆分为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!