Skip to content

Commit

Permalink
Add new function: 'initial'
Browse files Browse the repository at this point in the history
  • Loading branch information
Josef-Friedrich committed Feb 28, 2018
1 parent 8e7fc7a commit 1d524e1
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
19 changes: 19 additions & 0 deletions test/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,25 @@ def test_if_def_true_complete(self):
def test_if_def_false_complete(self):
self.parseEqual(u'%ifdef{trill,lol,troll}', u'troll')

# initial
def test_initial_use_first_character(self):
self.parseEqual(u'%initial{abc}', u'a')

def test_initial_german_umlaut(self):
self.parseEqual(u'%initial{ä}', u'a')

def test_initial_special_characters(self):
self.parseEqual(u'%initial{-a-}', u'a')

def test_initial_nothing(self):
self.parseEqual(u'%initial{}', u'_')

def test_initial_number(self):
self.parseEqual(u'%initial{3}', u'0')

def test_initial_lower(self):
self.parseEqual(u'%initial{A}', u'a')

# left
def test_left_literal(self):
self.parseEqual(u'%left{Schubert, 3}', u'Sch')
Expand Down
28 changes: 28 additions & 0 deletions tmep/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,34 @@ def tmpl_ifdefnotempty(self, field, trueval=u'', falseval=u''):
else:
return trueval

@staticmethod
def tmpl_initial(text):
"""
* synopsis: ``%initial{text}``
* description: Get the first character of a text in lowercase. The \
text is converted to ASCII. All non word characters are erased.
Only letters and numbers are preserved. If the first character is
a number, then the result is '0'.
:param string text: Input text to build initial from.
:return: A single character
"""
text = unidecode(text)
text = re.sub(r'[^a-zA-Z0-9]+', '', text)
text = text[0:1]
text = text.lower()
if not text:
return '_'

try:
int(text)
text = '0'
except:
pass

return text

@staticmethod
def tmpl_left(s, chars):
"""Get the leftmost characters of a string.
Expand Down

0 comments on commit 1d524e1

Please sign in to comment.