# -*- coding: utf-8 -*- """ obsapi: formatter module ~~~~~~~~~~~~~~~~~~~~~~~~ This module contains the FateFormatter class :copyright: Copyright (c) 2016 Scott Bahling, SUSE Linux GmbH :license: GPL-2.0, see COPYING for details """ import os from jinja2 import Environment, FileSystemLoader, TemplateNotFound, Template pkg_path = os.path.dirname(__file__) class Formatter(object): """Formatter Renders a string representation of an object based on Jinja2 templating. :param obj: Object to be formatted :param searchpath: Directory or list of directories to search for templates A template is selected from the searchpath based on the name of the object class with a '.j2' extension. If no template is found matching the class name, the default template (default.j2) will be used. The render() method will create a text output representing the object based on the selected template. """ default_searchpath = [os.path.expanduser('~/.obsapi/templates'), os.path.join(pkg_path, 'templates'), ] def __init__(self, obj, searchpath=None): searchpath = searchpath or self.default_searchpath self.env = Environment(loader=FileSystemLoader(searchpath)) self.obj = obj @property def template_name(self): return "%s.j2" % self.obj.__class__.__name__ @property def searchpath(self): return self.env.loader.searchpath @searchpath.setter def searchpath(self, path): self.env.loader.searchpath = path @property def template(self): try: return self.env.get_template(self.template_name) except TemplateNotFound: try: return self.env.get_template('default.j2') except: return Template('{{this.__class__.__name__}}') def render(self): return self.template.render(this=self.obj)