views/templates.py
author Sylvain Thénault <sylvain.thenault@logilab.fr>
Fri, 03 Feb 2017 14:29:10 +0100
changeset 65 b6d714abd494
parent 63 2f055b10dbce
child 66 245b53dbd993
permissions -rw-r--r--
[views] Fix flake8 error in main template

# -*- coding: utf-8 -*-
# copyright 2017 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr -- mailto:contact@logilab.fr
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""sherpa views/templates"""

from six import text_type as _

from logilab.common.decorators import monkeypatch

from cubicweb.utils import json_dumps, HTMLHead, UStringIO
from cubicweb.web.views import basetemplates

from . import jinja_render


# Bootstrap configuration.
basetemplates.TheMainTemplate.twbs_container_cls = 'container-fluid'


@monkeypatch(HTMLHead)
def add_onload(self, jscode):
    """original `add_onload` implementation use `$(cw)`
    but `cw` variable is not available
    in francearchive, use `$` instead"""
    self.add_post_inline_script(u"""$(function() {
  %s
});""" % jscode)


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
        print 'head', self._cw.html_headers.jsfiles
        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

        # left boxes
        left_boxes = list(self._cw.vreg['ctxcomponents'].poss_visible_objects(
            req, 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
        components = self.get_components(view, context='header-right')
        if components:
            w(u'<ul class="nav navbar-nav navbar-right">')
            for component in components:
                w(u'<li>')
                component.render(w=w)
                w(u'</li>')
            w(u'</ul>')
        right_header_component = stream.getvalue()

        # breadcrumbs
        stream = UStringIO()
        w = stream.write
        components = self.get_components(view, context='header-center')
        if components:
            for component in components:
                component.render(w=w)
        breadcrumbs = stream.getvalue()

        ctx = {
            'title': view.page_title(),
            '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._,
            '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')},
                ],
                'goTo_links': [
                    {'url': self._cw.build_url('SEDAArchiveUnit'),
                     'label': _("Unites d'archive")},
                    {'url': self._cw.build_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")},
                ]
            },
            'left_boxes': left_boxes_html,
            'footer': {
                'copyright': '### copyright ###',
                'contact': 'mailto:#'
            },
            'user': req.user.login,
            'current_url': req.relative_path(),
        }

        return ctx


def registration_callback(vreg):
    vreg.register_and_replace(SherpaMainTemplate, basetemplates.TheMainTemplate)