开发者

Truncate a string in mako template

I'd like to find a way开发者_StackOverflow to get a title to truncate if too long, like this:

'this is a title'
'this is a very long title that ...'

Is there a way to print a string in mako, and automatically truncate with "..." if greater than a certain number of characters?

Thanks.


Basic python solution:

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

This only cuts on spaces (if possible)

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


webhelpers goes hand-in-hand with MAKO templates. Use webhelpers.text.truncate - http://sluggo.scrapping.cc/python/WebHelpers/modules/text.html#webhelpers.text.truncate

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜