changeset 2159:5734b0994cf0

core (tools/common): template renderer first draft: jinja integration is being rewritten to be used not only in Libervia, this is a first step which put the renderer in backend/frontends tools. The renderer is mainly HTML oriented, but may be used for other files. sat_templates dependency is needed to use it.
author Goffi <goffi@goffi.org>
date Tue, 21 Feb 2017 21:01:39 +0100
parents 970a348d3fe9
children e67e8cd24141
files src/tools/common/template.py
diffstat 1 files changed, 75 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/tools/common/template.py	Tue Feb 21 21:01:39 2017 +0100
@@ -0,0 +1,75 @@
+#!/usr/bin/env python2
+# -*- coding: utf-8 -*-
+
+# SAT: a jabber client
+# Copyright (C) 2009-2016 Jérôme Poisson (goffi@goffi.org)
+
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, 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 Affero General Public License for more details.
+
+# You should have received a copy of the GNU Affero General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+""" template generation """
+
+from sat.core.constants import Const as C
+from sat.core import exceptions
+from sat.core.log import getLogger
+log = getLogger(__name__)
+import os.path
+try:
+    import sat_templates
+except ImportError:
+    raise exceptions.MissingModule(u'sat_templates module is not available, please install it or check your path to use template engine')
+else:
+    sat_templates  # to avoid pyflakes warning
+
+try:
+    import jinja2
+except:
+    raise exceptions.MissingModule(u'Missing module jinja2, please install it from http://jinja.pocoo.org or with pip install jinja2')
+
+
+class Renderer(object):
+
+    def __init__(self, host): # , template_dir=None):
+        self.host = host
+        self.base_dir = os.path.dirname(sat_templates.__file__)
+        self.theme = u'default'  # FIXME: temporary, template should be selected in render()
+        self.env = jinja2.Environment(
+            loader=jinja2.PackageLoader('sat_templates', self.theme),
+            autoescape=jinja2.select_autoescape(['html', 'xhtml', 'xml']),
+            trim_blocks=True,
+            lstrip_blocks=True,
+            )
+        # we want to have access to SàT constants in templates
+        self.env.globals[u'C'] = C
+
+    def render(self, template_path, theme=u"default", css_file=u"style.css", css_inline=False, **kwargs):
+        """render a template
+
+        @param template_path(unicode): path of the template to render (e.g. blog/articles.html)
+        @param theme(unicode): template theme
+        @param css_file(unicode): path to CSS file (relative to template dir, or absolute)
+        @param css_inline(bool): if True, CSS will be embedded in the HTML page
+        @param **kwargs: variable to transmit to the template
+        """
+
+        # TODO: handle theme
+        template = self.env.get_template(template_path)
+        if css_inline:
+            css_file_path = os.path.join(self.getStaticDir(template_path), css_file)
+            with open(css_file_path, 'r') as f:
+                kwargs[u"css_content"] = f.read()
+        return template.render(theme=theme, css_file=css_file, css_inline=css_inline, **kwargs)
+
+    def getStaticDir(self, template_path):
+        template_base = template_path.split(u'/')[0]
+        return os.path.join(self.base_dir, self.theme, template_base, "static")