2010-10-12 24 views
1

Je voudrais trouver un moyen d'obtenir un titre de tronquer si elle est trop longue, comme ceci:tronquer une chaîne dans le modèle mako

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

Est-il possible d'imprimer une chaîne dans mako, et automatiquement tronquer avec "..." si plus grand qu'un certain nombre de caractères?

Merci.

Répondre

2

solution python de base:

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

Cela ne coupes sur les espaces (si 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