Обрезать строку в шаблоне мако - PullRequest
1 голос
/ 12 октября 2010

Я хотел бы найти способ получить заголовок для усечения, если он слишком длинный, например:

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

Есть ли способ напечатать строку в mako и автоматически обрезать ее с помощью "...", если число символов превышает определенное число?

Спасибо.

Ответы [ 2 ]

2 голосов
/ 12 октября 2010

Базовое решение 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
0 голосов
/ 01 марта 2013

webhelpers идет рука об руку с шаблонами MAKO.Используйте webhelpers.text.truncate - http://sluggo.scrapping.cc/python/WebHelpers/modules/text.html#webhelpers.text.truncate

...