[views] Cleanup and refactoring of the SherpaMainTemplate
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Fri, 03 Feb 2017 14:48:11 +0100
changeset 71 a1789d380f77
parent 68 e4c9b0133b6f
child 76 216ac18640f8
[views] Cleanup and refactoring of the SherpaMainTemplate
views/templates.py
--- a/views/templates.py	Fri Feb 03 14:31:37 2017 +0100
+++ b/views/templates.py	Fri Feb 03 14:48:11 2017 +0100
@@ -1,3 +1,4 @@
+# -*- coding: utf-8
 # copyright 2017 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 # contact http://www.logilab.fr -- mailto:contact@logilab.fr
 #
@@ -17,7 +18,6 @@
 
 from logilab.common.decorators import monkeypatch
 
-from cubicweb import _
 from cubicweb.utils import json_dumps, HTMLHead, UStringIO
 from cubicweb.web.views import basetemplates
 
@@ -40,51 +40,21 @@
 
 class SherpaMainTemplate(basetemplates.TheMainTemplate):
 
-    def _handle_added_resources(self, tmpl_context):
-        """fetch all resources added with add_{js,css}, etc.
-
-        and backport them into ``tmpl_context`` to feed the main jinja template
-        """
-        # handle define_var() calls
-        var_stmts = [(var, json_dumps(value))
-                     for var, value, override in self._cw.html_headers.jsvars]
-        tmpl_context['js_vars'] = var_stmts
-
-        # handle add_js() calls
-        current_jsfiles = tmpl_context['jsfiles']
-        for jsfile in self._cw.html_headers.jsfiles:
-            if jsfile not in current_jsfiles:
-                current_jsfiles.append(jsfile)
-
-        # handle add_onload() calls
-        tmpl_context['inline_scripts'] = self._cw.html_headers.post_inlined_scripts
-        # handle add_css() calls
-        current_cssfiles = tmpl_context['cssfiles']
-        for cssfile, media in self._cw.html_headers.cssfiles:
-            if cssfile not in current_cssfiles:
-                current_cssfiles.append(cssfile)
-
     def call(self, view):
         self.set_request_content_type()
         self._cw.html_headers.define_var('BASE_URL', self._cw.build_url(''))
         context = self.template_context(view)
-        page_content = view.render()
-        context.update(getattr(view, 'template_context', lambda: {})())
-        self._handle_added_resources(context)
-        context['page_content'] = page_content
         self.w(jinja_render('maintemplate', **context))
 
     def template_context(self, view):
-        req = self._cw
-
+        """Return the main-template's context."""
         # left boxes
         left_boxes = list(self._cw.vreg['ctxcomponents'].poss_visible_objects(
-            req, rset=self.cw_rset, view=view, context='left'))
+            self._cw, rset=self.cw_rset, view=view, context='left'))
         stream = UStringIO()
         for box in left_boxes:
             box.render(w=stream.write, view=view)
         left_boxes_html = stream.getvalue()
-
         # header
         stream = UStringIO()
         w = stream.write
@@ -97,7 +67,6 @@
                 w(u'</li>')
             w(u'</ul>')
         right_header_component = stream.getvalue()
-
         # breadcrumbs
         stream = UStringIO()
         w = stream.write
@@ -107,52 +76,80 @@
                 component.render(w=w)
         breadcrumbs = stream.getvalue()
 
-        ctx = {
+        page_content = view.render()
+
+        ctx = self.base_context()
+        url = self._cw.build_url
+        ctx.update({
             'title': view.page_title(),
+            'page_content': page_content,
             'breadcrumbs': breadcrumbs,
-            'base_url': self._cw.build_url(''),
-            'data_url': self._cw.datadir_url,
-            'cssfiles': self._cw.uiprops['STYLESHEETS'],
-            'jsfiles': self._cw.uiprops['JAVASCRIPTS'],
-            'page_id': 'contentmain',
             'right_header_component': right_header_component,
-            '_': self._cw._,
+            'left_boxes': left_boxes_html,
             'side_box': {
                 'resources': [
-                    {'url': self._cw.build_url('shema_seda'),
-                     'label': _('Schema du SEDA 2.0')},
-                    {'url': self._cw.build_url('dictionnaire'),
-                     'label': _('Dictionnaire des balises')},
-                    {'url': self._cw.build_url('documentation_fonctionnelle'),
-                     'label': _('Documentation fonctionnelle')},
-                    {'url': self._cw.build_url('documentation_technique'),
-                     'label': _('Documentation technique')},
+                    {'url': url('shema_seda'),
+                     'label': u'Schéma du SEDA 2.0'},
+                    {'url': url('dictionnaire'),
+                     'label': 'Dictionnaire des balises'},
+                    {'url': url('documentation_fonctionnelle'),
+                     'label': 'Documentation fonctionnelle'},
+                    {'url': url('documentation_technique'),
+                     'label': 'Documentation technique'},
                 ],
                 'goTo_links': [
-                    {'url': self._cw.build_url('SEDAArchiveUnit'),
-                     'label': _("Unites d'archive")},
-                    {'url': self._cw.build_url('SEDAArchiveTransfer'),
-                     'label': _('Profils SEDA')}
+                    {'url': url('SEDAArchiveUnit'),
+                     'label': u"Unités d'archive"},
+                    {'url': url('SEDAArchiveTransfer'),
+                     'label': 'Profils SEDA'}
                 ],
                 'navigation_Link': [
-                    {'url': self._cw.build_url('project'),
-                     'label': _('Le projet Sherpa')},
-                    {'url': self._cw.build_url('utilisation'),
-                     'label': _("Mode d'emploi")},
-                    {'url': self._cw.build_url('seda'),
-                     'label': _("Le SEDA")},
+                    {'url': url('project'),
+                     'label': 'Le projet Sherpa'},
+                    {'url': url('utilisation'),
+                     'label': "Mode d'emploi"},
+                    {'url': url('seda'),
+                     'label': "Le SEDA"},
                 ]
             },
-            'left_boxes': left_boxes_html,
             'footer': {
                 'copyright': '### copyright ###',
                 'contact': 'mailto:#'
             },
+        })
+        ctx.update(getattr(view, 'template_context', lambda: {})())
+
+        return ctx
+
+    def base_context(self):
+        """Return a basic context using standard cubicweb information including
+        all resources added with add_{js,css}, etc.
+        """
+        req = self._cw
+        context = {
+            'base_url': req.build_url(''),
+            'data_url': req.datadir_url,
+            'page_id': 'contentmain',
+            '_': req._,
             'user': req.user.login,
             'current_url': req.relative_path(),
         }
 
-        return ctx
+        # handle define_var() calls
+        context['js_vars'] = [(var, json_dumps(val))
+                              for var, val, override in req.html_headers.jsvars]
+        # handle add_js() calls
+        context['jsfiles'] = list(req.uiprops['JAVASCRIPTS'])
+        for jsfile in req.html_headers.jsfiles:
+            context['jsfiles'].append(jsfile)
+        # handle add_onload() calls
+        context['inline_scripts'] = req.html_headers.post_inlined_scripts
+        # handle add_css() calls
+        context['cssfiles'] = list(req.uiprops['STYLESHEETS'])
+        for cssfile, media in req.html_headers.cssfiles:
+            context['cssfiles'].append(cssfile)  # XXX media?
+
+        return context
 
 
 def registration_callback(vreg):