在mako模板中截断字符串
我想找个方法,如果标题太长就让它变短,像这样:
'this is a title'
'this is a very long title that ...'
有没有办法在mako中打印一个字符串,如果字符数超过某个限制,就自动用“...”来表示省略呢?
谢谢。
2 个回答
0
webhelpers
和 MAKO 模板是配套使用的。你可以使用 webhelpers.text.truncate
这个功能,具体可以查看这个链接:http://sluggo.scrapping.cc/python/WebHelpers/modules/text.html#webhelpers.text.truncate
2
基本的Python解决方案:
MAXLEN = 15
def title_limit(title, limit):
if len(title) > limit:
title = title[:limit-3] + "..."
return title
blah = "blah blah blah blah blah"
title_limit(blah) # returns 'blah blah bla...'
这个方法只会在空格的地方进行切割(如果可以的话)
def find_rev(str,target,start):
str = str[::-1]
index = str.find(target,len(str) - start)
if index != -1:
index = len(str) - index
return index
def title_limit(title, limit):
if len(title) <= limit: return title
cut = find_rev(title, ' ', limit - 3 + 1)
if cut != -1:
title = title[:cut-1] + "..."
else:
title = title[:limit-3] + "..."
return title
print title_limit('The many Adventures of Bob', 10) # The...
print title_limit('The many Adventures of Bob', 20) # The many...
print title_limit('The many Adventures of Bob', 30) # The many Adventures of Bob