Created
October 31, 2012 10:59
-
-
Save marselester/3986441 to your computer and use it in GitHub Desktop.
Django template tag which fits words into block.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@register.simple_tag | |
def fit_words_to_block(src_text, max_str_len, max_str_qty=None): | |
"""Truncates words from text thus they might be fitted to size of symbols block. | |
Also it can limit quantity of strings. | |
""" | |
if not src_text.strip(): | |
return u'' | |
words = [] | |
for word in src_text.split(): | |
if len(word) > max_str_len: | |
splitted_word = split_sequence_by_len(word, max_str_len) | |
words.extend(splitted_word) | |
else: | |
words.append(word) | |
if max_str_qty is not None: | |
free_str_qty = max_str_qty | |
list_of_strings = [] | |
string = words.pop(0) | |
for word in words: | |
pretendent_word = u' ' + word | |
future_len_of_string = len(string) + len(pretendent_word) | |
if max_str_len >= future_len_of_string: | |
string += pretendent_word | |
else: | |
free_str_qty -= 1 | |
list_of_strings.append(string) | |
string = pretendent_word | |
if free_str_qty == 0: | |
break | |
else: | |
list_of_strings.append(string) | |
truncated_text = u''.join(list_of_strings) | |
else: | |
truncated_text = u' '.join(words) | |
return truncated_text | |
def split_sequence_by_len(sequence, length): | |
"""Splits sequence to equal chunks by length.""" | |
chunk_start_indexes = xrange(0, len(sequence), length) | |
return [sequence[index:index + length] for index in chunk_start_indexes] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment