Kürzt eine Zeichenkette in mako Vorlage
Frage
Ich möchte einen Weg finden, um einen Titel zu truncate wenn sie zu lange erhalten, wie folgt:
'this is a title'
'this is a very long title that ...'
Gibt es eine Möglichkeit, eine Zeichenfolge in mako zu drucken und automatisch gestutzt mit „...“, wenn mehr als eine bestimmte Anzahl von Zeichen?
Danke.
Lösung
Grund Python Lösung:
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...'
Dies ist nur Schnitte auf Räume (wenn möglich)
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
Andere Tipps
webhelpers
geht Hand in Hand mit MAKO-Vorlagen. Verwenden webhelpers.text.truncate
- http://sluggo.scrapping.cc/ python / WebHelpers / modules / text.html # webhelpers.text.truncate
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow