[web] safety belt to avoid overriding pageid with loadxhtml() stable
authorAdrien Di Mascio <Adrien.DiMascio@logilab.fr>
Fri, 13 Nov 2009 10:47:26 +0100
branchstable
changeset 3838 9cc134372bf8
parent 3837 0cb409871d42
child 3841 b2598c9eeffc
[web] safety belt to avoid overriding pageid with loadxhtml() HtmlHeaders.define_var() now accepts a third optional 'override' paramater. If set to False, the variable won't be evaluated if it's already defined in the page.
utils.py
web/request.py
--- a/utils.py	Fri Nov 13 09:16:28 2009 +0100
+++ b/utils.py	Fri Nov 13 10:47:26 2009 +0100
@@ -214,8 +214,16 @@
     def add_raw(self, rawheader):
         self.write(rawheader)
 
-    def define_var(self, var, value):
-        self.jsvars.append( (var, value) )
+    def define_var(self, var, value, override=True):
+        """adds a javascript var declaration / assginment in the header
+
+        :param var: the variable name
+        :param value: the variable value (as a raw python value,
+                      it will be jsonized later)
+        :param override: if False, don't set the variable value if the variable
+                         is already defined. Default is True.
+        """
+        self.jsvars.append( (var, value, override) )
 
     def add_post_inline_script(self, content):
         self.post_inlined_scripts.append(content)
@@ -269,8 +277,12 @@
         # 1/ variable declaration if any
         if self.jsvars:
             w(u'<script type="text/javascript"><!--//--><![CDATA[//><!--\n')
-            for var, value in self.jsvars:
-                w(u'%s = %s;\n' % (var, dumps(value)))
+            for var, value, override in self.jsvars:
+                vardecl = u'%s = %s;' % (var, dumps(value))
+                if not override:
+                    vardecl = (u'if (typeof %s == "undefined") {%s}' %
+                               (var, vardecl))
+                w(vardecl + u'\n')
             w(u'//--><!]]></script>\n')
         # 2/ css files
         for cssfile, media in self.cssfiles:
--- a/web/request.py	Fri Nov 13 09:16:28 2009 +0100
+++ b/web/request.py	Fri Nov 13 10:47:26 2009 +0100
@@ -96,7 +96,7 @@
         if pid is None:
             pid = make_uid(id(self))
         self.pageid = pid
-        self.html_headers.define_var('pageid', pid)
+        self.html_headers.define_var('pageid', pid, override=False)
 
     def set_connection(self, cnx, user=None):
         """method called by the session handler when the user is authenticated