diff sat_frontends/jp/output_template.py @ 2671:0fa217fafabf

tools (common/template), jp: refactoring to handle multiple sites: - site can now be specified in template header before theme, for instance: (some_site/some_theme)path/to/template.ext - absolute template paths are now implemented, but Renderer must be instanciated with trusted to True for security reason (it's the case for jp) - a new "front_url_filter" callable can be given to Renderer, which will convert template path to URL seen by end-user (default to real path). - the "front_url_filter" can be used in templates with… "front_url" filter - template_data is a new named tuple available in templates, which give site, theme and template relative URL - search order is site/theme, site/default_theme, and default/default_theme where default link to sat_pubsub templates - when loading CSS files, files with _noscript suffixes are now loaded, and used when javascript is not available - "styles_extra.css" is also loaded before "styles.css", useful when a theme want to reuse default style, and just override some rules - new site can be specified in sat.conf [DEFAULT] section, using sites_path_public_dict or sites_path_private_dict (where sites_path_private_dict won't be used in public frontends, like Libervia) - "private" argument of Renderer tells the renderer to load private sites or not - templates are now loaded from "templates" subdirectory, to differenciate them from other data like i18n - jp template output has been updated to handle those changes, and to manage absolute templates
author Goffi <goffi@goffi.org>
date Mon, 10 Sep 2018 08:58:18 +0200
parents 56f94936df1e
children 003b8b4b56a7
line wrap: on
line diff
--- a/sat_frontends/jp/output_template.py	Fri Aug 31 17:18:51 2018 +0200
+++ b/sat_frontends/jp/output_template.py	Mon Sep 10 08:58:18 2018 +0200
@@ -21,7 +21,10 @@
 
 from sat_frontends.jp.constants import Const as C
 from sat.core.i18n import _
+from sat.core import log
 from sat.tools.common import template
+from functools import partial
+import logging
 import webbrowser
 import tempfile
 import os.path
@@ -38,6 +41,19 @@
         self.host = jp
         jp.register_output(C.OUTPUT_COMPLEX, TEMPLATE, self.render)
 
+    def _front_url_tmp_dir(self, ctx, relative_url, tmp_dir):
+        """Get front URL for temporary directory"""
+        template_data = ctx[u'template_data']
+        return u"file://" + os.path.join(tmp_dir, template_data.theme, relative_url)
+
+    def _do_render(self, template_path, css_inline, **kwargs):
+        try:
+            return self.renderer.render(template_path, css_inline=css_inline, **kwargs)
+        except template.TemplateNotFound:
+            self.host.disp(_(u"Can't find requested template: {template_path}")
+                .format(template_path=template_path), error=True)
+            self.host.quit(C.EXIT_NOT_FOUND)
+
     def render(self, data):
         """render output data using requested template
 
@@ -55,23 +71,23 @@
             template_path = cmd.TEMPLATE
         except AttributeError:
             if not "template" in cmd.args.output_opts:
-                self.host.disp(
-                    u"no default template set for this command, "
-                    u"you need to specify a template using --oo template=[path/to/template.html]",
+                self.host.disp(_(
+                    u"no default template set for this command, you need to specify a "
+                    u"template using --oo template=[path/to/template.html]"),
                     error=True,
                 )
                 self.host.quit(C.EXIT_BAD_ARG)
 
         options = self.host.parse_output_options()
         self.host.check_output_options(OPTIONS, options)
-        self.renderer = template.Renderer(self.host)
         try:
             template_path = options["template"]
         except KeyError:
             # template is not specified, we use default one
             pass
         if template_path is None:
-            self.host.disp(u"Can't parse template, please check its syntax", error=True)
+            self.host.disp(_(u"Can't parse template, please check its syntax"),
+                           error=True)
             self.host.quit(C.EXIT_BAD_ARG)
 
         try:
@@ -82,28 +98,41 @@
             kwargs = mapping_cb(data)
 
         css_inline = u"inline-css" in options
-        rendered = self.renderer.render(template_path, css_inline=css_inline, **kwargs)
 
         if "browser" in options:
             template_name = os.path.basename(template_path)
             tmp_dir = tempfile.mkdtemp()
-            self.host.disp(
-                _(
-                    u"Browser opening requested.\nTemporary files are put in the following directory, "
-                    u"you'll have to delete it yourself once finished viewing: {}"
-                ).format(tmp_dir)
-            )
+            front_url_filter = partial(self._front_url_tmp_dir, tmp_dir=tmp_dir)
+            self.renderer = template.Renderer(
+                self.host, front_url_filter=front_url_filter, trusted=True)
+            rendered = self._do_render(template_path, css_inline=css_inline, **kwargs)
+            self.host.disp(_(
+                u"Browser opening requested.\n"
+                u"Temporary files are put in the following directory, you'll have to "
+                u"delete it yourself once finished viewing: {}").format(tmp_dir))
             tmp_file = os.path.join(tmp_dir, template_name)
             with open(tmp_file, "w") as f:
                 f.write(rendered.encode("utf-8"))
             theme, theme_root_path = self.renderer.getThemeAndRoot(template_path)
+            if theme is None:
+                # we have an absolute path
+                webbrowser
             static_dir = os.path.join(theme_root_path, C.TEMPLATE_STATIC_DIR)
             if os.path.exists(static_dir):
+                # we have to copy static files in a subdirectory, to avoid file download
+                # to be blocked by same origin policy
                 import shutil
-
                 shutil.copytree(
                     static_dir, os.path.join(tmp_dir, theme, C.TEMPLATE_STATIC_DIR)
                 )
             webbrowser.open(tmp_file)
         else:
+            # FIXME: Q&D way to disable template logging
+            #        logs are overcomplicated, and need to be reworked
+            template_logger = log.getLogger(u"sat.tools.common.template")
+            template_logger.log = lambda *args: None
+
+            logging.disable(logging.WARNING)
+            self.renderer = template.Renderer(self.host, trusted=True)
+            rendered = self._do_render(template_path, css_inline=css_inline, **kwargs)
             self.host.disp(rendered)