comparison frontends/src/jp/output_template.py @ 2163:75667727c500

jp (output): template output first draft: template output use the new template renderer and data_objects module in backend tools. Options can be specified: template to give a direct path to template, browser to display result directly, inline-css to include css in the HTML page. Default template can be specified in command's TEMPLATE attribute, and a template_data_mapping method is called if it exists to map data to what is expected by the template.
author Goffi <goffi@goffi.org>
date Tue, 21 Feb 2017 21:01:40 +0100
parents
children f472179305a1
comparison
equal deleted inserted replaced
2162:c9a67eb5bf72 2163:75667727c500
1 #! /usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # jp: a SàT command line tool
5 # Copyright (C) 2009-2016 Jérôme Poisson (goffi@goffi.org)
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 """Standard outputs"""
20
21
22 from sat_frontends.jp.constants import Const as C
23 from sat.core.i18n import _
24 from sat.tools.common import template
25 import webbrowser
26 import tempfile
27 import os.path
28
29 __outputs__ = ["Template"]
30 TEMPLATE = u'template'
31 OPTIONS = {u'template', u'browser', u'inline-css'}
32
33
34 class Template(object):
35 """outputs data using SàT templates"""
36
37 def __init__(self, jp):
38 self.host = jp
39 jp.register_output(C.OUTPUT_COMPLEX, TEMPLATE, self.render)
40 self.renderer = template.Renderer(jp)
41
42 def parse_options(self, options):
43 options_dict = {}
44 for option in options:
45 try:
46 key, value = option.split(u'=', 1)
47 except ValueError:
48 key, value = option, None
49 options_dict[key.strip()] = value.strip() if value is not None else None
50 return options_dict
51
52 def render(self, data):
53 """render output data using requested template
54
55 template to render the data can be either command's TEMPLATE or
56 template output_option requested by user.
57 @param data(dict): data is a dict which map from variable name to use in template
58 to the variable itself.
59 command's template_data_mapping attribute will be used if it exists to convert
60 data to a dict usable by the template.
61 """
62 cmd = self.host.command
63 options = self.parse_options(cmd.args.output_opts)
64 if not OPTIONS.issuperset(options):
65 self.host.disp(u"The following output options are invalid: {invalid_options}".format(
66 invalid_options = u', '.join(set(options).difference(OPTIONS))),
67 error=True)
68 self.host.quit(C.EXIT_BAD_ARG)
69 try:
70 template_path = cmd.TEMPLATE
71 except AttributeError:
72 if not 'template' in cmd.args.output_opts:
73 self.host.disp(u'no default template set for this command, '
74 u'you need to specify a template using --oo template=[path/to/template.html',
75 error=True)
76 self.host.quit(C.EXIT_BAD_ARG)
77 try:
78 template_path = options['template']
79 except KeyError:
80 # template is not specified, we use default one
81 pass
82 if template_path is None:
83 self.host.disp(u"Can't parse template, please check its syntax",
84 error=True)
85 self.host.quit(C.EXIT_BAD_ARG)
86
87 try:
88 mapping_cb = cmd.template_data_mapping
89 except AttributeError:
90 kwargs = data
91 else:
92 kwargs = mapping_cb(data)
93
94 css_inline = u'inline-css' in options
95 rendered = self.renderer.render(template_path, css_inline=css_inline, **kwargs)
96
97 if 'browser' in options:
98 template_name = os.path.basename(template_path)
99 tmp_dir = tempfile.mkdtemp()
100 self.host.disp(_(u"Browser opening requested.\nTemporary files are put in the following directory, "
101 u"you'll have to delete it yourself once finished viewing: {}").format(tmp_dir))
102 tmp_file = os.path.join(tmp_dir, template_name)
103 with open(tmp_file, 'w') as f:
104 f.write(rendered.encode('utf-8'))
105 static_dir = self.renderer.getStaticDir(template_path)
106 if os.path.exists(static_dir):
107 import shutil
108 shutil.copytree(static_dir, os.path.join(tmp_dir, u'static'))
109 webbrowser.open(tmp_file)
110 else:
111 self.host.disp(rendered)