view src/tools/common/template.py @ 2160:e67e8cd24141

core (tools/common): data objects first draft: this module aims is to help manipulate complex data from bridge, mainly for the template system. It is in common and not only in frontends as it may be used in some case by backend, if it needs to use template system in the future.
author Goffi <goffi@goffi.org>
date Tue, 21 Feb 2017 21:01:40 +0100
parents 5734b0994cf0
children f472179305a1
line wrap: on
line source

#!/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")