Commit 8fb3a485 authored by Adam D. Barratt's avatar Adam D. Barratt

debrelease.jinja: new module to handle Jinja2 templating

The initial version of this module is mostly abstracred out of the
"point-release-mail" tool.
Signed-off-by: 's avatarAdam D. Barratt <adam@adam-barratt.org.uk>
parent a1a7d7ae
## vim:set et ts=4 sw=4:
#
# jinja.py: convenience functions for dealing with Jinja2 templating
#
# (C) 2018 Adam D. Barratt <adam@adam-barratt.org.uk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Dependencies (expressed in Debian packages):
# * python3-jinja2
import re
from textwrap import wrap
from jinja2 import Environment
from jinja2.filters import environmentfilter
class filters(object):
def capfirst(s):
if s:
return s[0].capitalize() + s[1:]
else:
return ''
def nesteddictsort(thedict, bykey, reverse=False):
return sorted(thedict.items(), key=lambda x: x[1][bykey], reverse=reverse)
@environmentfilter
def parawordwrap(environment, s, width=79, break_long_words=True, replace_whitespace=True,
wrapstring=None):
if not wrapstring:
wrapstring = environment.newline_sequence
return wrapstring.join(wrap(s, width=width, expand_tabs=False,
replace_whitespace=replace_whitespace,
break_long_words=break_long_words))
def lrjust(strings, width, pad_char=' '):
return '{}{}{}'.format(strings[0], pad_char * (width - len(strings[0]) - len(strings[1])), strings[1])
def escape_for_wml(res):
res = res.replace('&', '&amp;')
res = res.replace('>', '&gt;')
res = res.replace('<', '&lt;')
res = re.sub(r'\"(.+?)\"', r'<q>\1</q>', res)
return res
class jinja(object):
def __init__(self):
# Enable the use of the "do" statement in templates
self.env = Environment (
extensions=['jinja2.ext.do']
)
self.filters = {
'capfirst': filters.capfirst,
'lrjust': filters.lrjust,
'nesteddictsort': filters.nesteddictsort,
'parawordwrap': filters.parawordwrap,
'wmlescape': filters.escape_for_wml,
}
self.env.filters.update(self.filters)
def render_jinja_template(self, template, *args, **kwargs):
# The template is a list of lines, but jinja expects a
# single string
t = self.env.from_string(''.join(template))
return t.render(*args, **kwargs)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment