
import os
from mako.template import Template
from mako.lookup import TemplateLookup
from mako import exceptions

_mydir = os.path.join(os.path.dirname(__file__), "templates")
_mytemplates = TemplateLookup(directories=_mydir,
                              #module_directory="templates\\modules",
                              cache_enabled = False,
                              output_encoding="utf-8",
                              encoding_errors="replace")

print("Initialised template dir '{0}'...".format(_mydir))


def process_template(name, **kwargs):
    template = get_template(name)

    if template:
      try:
          return template.render(**kwargs)
      except:
          print(exceptions.text_error_template().render())


def get_template(name):
    try:
        return _mytemplates.get_template(name)
    except exceptions.TemplateLookupException as e:
        print("No template '{0}' found: {1}".format(name, e))
        return None


def define_template(tmpl):
    new_template = Template(tmpl, lookup=_mytemplates)
    return new_template

