Extend jinja_static_view to handle path registration
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Tue, 28 Feb 2017 11:25:29 +0100
changeset 183 2b4c0dca2466
parent 182 c2b5337dbc99
child 184 2a711576ebdf
Extend jinja_static_view to handle path registration Also add `ignore_baseclass_rules = True` to our rewriter, else we ends up checking the base views again and again (one for the cubicweb class, another for its subclass in the seda cube, another for its subclass in this cube, etc...).
cubicweb_sherpa/views/__init__.py
--- a/cubicweb_sherpa/views/__init__.py	Tue Feb 28 10:42:00 2017 +0100
+++ b/cubicweb_sherpa/views/__init__.py	Tue Feb 28 11:25:29 2017 +0100
@@ -20,6 +20,7 @@
 from cubicweb.view import View
 from cubicweb.web.views import urlrewrite, startup
 
+_REWRITE_RULES = []
 _JINJA_ENV = Environment(loader=PackageLoader('cubicweb_sherpa.views'),
                          autoescape=select_autoescape(enabled_extensions=('html',)))
 
@@ -44,15 +45,23 @@
                             data_url=self._cw.datadir_url))
 
 
-def jinja_static_view(template_name, title=None, regid=None):
+def jinja_static_view(template_name, title=None, regid=None, path=None):
     """Generate a sub-class of JinjaStaticView parametrized with its `template_name` and `title`.
 
-    `__regid__` is built by prepending 'sherpa.' to template_name.
+    `__regid__` is built by prepending 'sherpa.' to template_name or may be explicitly specified
+    using `regid`.
+
+    A path to access to view is automatically generated and will match `template_name` unless
+    explicitly specified using `path` argument.
     """
     class_name = template_name.capitalize() + 'View'
     if regid is None:
         regid = 'sherpa.' + template_name
 
+    if path is None:
+        path = '/' + template_name
+    _REWRITE_RULES.append((path, {'vid': regid}))
+
     return type(class_name, (JinjaStaticView,), {'__regid__': regid,
                                                  'template_name': template_name,
                                                  'title': title})
@@ -61,16 +70,15 @@
 ProjectView = jinja_static_view('project', u'Sherpa un générateur de profils')
 UtilisationView = jinja_static_view('utilisation', u'Pour commencer')
 SedaView = jinja_static_view('seda', u'Le SEDA')
-IndexView = jinja_static_view('index', regid='index')
+IndexView = jinja_static_view('index', regid='index', path='/')
 
 
+# add our rewrite rules, has to be done once the list if filled because of metaclass magic
 class SherpaReqRewriter(urlrewrite.SimpleReqRewriter):
-    rules = [
-        ('/', dict(vid='sherpa.index')),
-        ('/project', dict(vid='sherpa.project')),
-        ('/utilisation', dict(vid='sherpa.utilisation')),
-        ('/seda', dict(vid='sherpa.seda')),
-    ]
+    ignore_baseclass_rules = True
+    global _REWRITE_RULES
+    rules = tuple(_REWRITE_RULES)
+    del _REWRITE_RULES
 
 
 def registration_callback(vreg):