Skip to content

Instantly share code, notes, and snippets.

@bsmithgall
Created August 3, 2015 18:19
Show Gist options
  • Save bsmithgall/3a94e0cbce94e56831dc to your computer and use it in GitHub Desktop.
Save bsmithgall/3a94e0cbce94e56831dc to your computer and use it in GitHub Desktop.
python titlecase filter for jinja
# modified from https://gist.github.com/bsmithgall/372de43205804a2279c9
SMALL_WORDS = re.compile(r'^(a|an|and|as|at|but|by|en|etc|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$', re.I)
SPACE_SPLIT = re.compile(r'[\t ]')
# taken from http://stackoverflow.com/a/267405
CAP_WORDS = re.compile(r'^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$')
PUNC_REGEX = re.compile(r'[{}]'.format(re.escape(string.punctuation)))
# taken from python-titlecase: https://github.com/ppannuto/python-titlecase/blob/master/titlecase/__init__.py#L27
UC_INITIALS = re.compile(r'^(?:[A-Z]{1}\.{1}|[A-Z]{1}\.{1}[A-Z]{1})+$', re.I)
def better_title(string):
'''drop in replacement for jinja default title filter
modified from https://gist.github.com/bsmithgall/372de43205804a2279c9
'''
rv = []
for word in re.split(SPACE_SPLIT, string):
_cleaned_word = PUNC_REGEX.sub('', word)
if re.match(UC_INITIALS, word):
rv.append(word.upper())
elif re.match(SMALL_WORDS, _cleaned_word.strip()):
rv.append(word.lower())
elif word.startswith('('):
new_string = '('
new_string += better_title(word.lstrip('('))
rv.append(new_string)
elif re.match(CAP_WORDS, _cleaned_word):
rv.append(word.upper())
else:
rv.append(word[0].upper() + word[1:].lower())
return ' '.join(rv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment