【发布时间】:2020-12-23 08:45:48
【问题描述】:
在我的 Django 项目中,我需要根据特定字符将字符串拆分为模板。
str1 = "Part1 - Part2"
在纯 python 中我会这样做:
part1 = str1.split("-",1)[0]
part2 = str1.split("-",1)[1]
我尝试使用 django 模板:
{{ str1|split:'-'|first }}
但我给出一个错误:
过滤器无效:'split'
有人可以帮助我在 django 模板中拆分我的变量,并根据特定的字符只取第一部分或第二部分?
提前非常感谢
【问题讨论】:
-
这能回答你的问题吗? Django templates - split string to array
-
我猜Django中没有拆分标签。您将需要自己实现它。我找到了这个解决方案moonbooks.org/Articles/…
-
嗯抱歉,但我不明白如何根据该链接解决我的问题。谢谢
-
这个stackoverflow问题-stackoverflow.com/questions/8317537/…回答你的问题了吗?
-
您可以在 django 中实现自己的拆分过滤器。 docs.djangoproject.com/en/3.1/howto/custom-template-tags 这是实现自定义模板标签的官方文档
标签: python django django-templates