1# -*- coding: ascii -*- 2""" 3web2ldap.app.tmpl - template file handling 4 5web2ldap - a web-based LDAP Client, 6see https://www.web2ldap.de for details 7 8(c) 1998-2021 by Michael Stroeder <michael@stroeder.com> 9 10This software is distributed under the terms of the 11Apache License Version 2.0 (Apache-2.0) 12https://www.apache.org/licenses/LICENSE-2.0 13""" 14 15import os 16 17from . import ErrorExit 18 19 20def get_variant_filename(pathname, variantlist): 21 """ 22 returns variant filename 23 """ 24 checked_set = set() 25 for val in variantlist: 26 # Strip subtags 27 val = val.lower().split('-', 1)[0] 28 if val == 'en': 29 variant_filename = pathname 30 else: 31 variant_filename = '.'.join((pathname, val)) 32 if val not in checked_set and os.path.isfile(variant_filename): 33 break 34 checked_set.add(val) 35 else: 36 variant_filename = pathname 37 return variant_filename 38 39 40def read_template(app, config_key, form_desc='', tmpl_filename=None): 41 if not tmpl_filename: 42 tmpl_filename = app.cfg_param(config_key, None) 43 if not tmpl_filename: 44 raise ErrorExit('No template specified for %s.' % (form_desc)) 45 tmpl_filename = get_variant_filename(tmpl_filename, app.form.accept_language) 46 try: 47 # Read template from file 48 with open(tmpl_filename, 'rb') as tmpl_fileobj: 49 tmpl_str = tmpl_fileobj.read().decode('utf-8') 50 except IOError: 51 raise ErrorExit('I/O error during reading %s template file.' % (form_desc)) 52 return tmpl_str 53