You are here: Home Blog Topics browser view
Follow us on Twitter
just launched a new Plone site, http://lnkd.in/km2Wpj , for a Kansas City company that builds custom counter tops. Aug 18, 2010 10:03 PM
Injecting Plone variables into javascript:   Step 1: Create a class to output the javascript I created a file in s... http://bit.ly/bjzIzb Jun 22, 2010 10:32 AM
@natea Thx. I'm sitting, writing a presentation for Generic Setup. Your Plone 4 summary is way useful! Apr 27, 2010 09:49 PM
Reminder: Tomorrow is Colorado World Plone Day at the NREL Visitor Center , Golden, CO. http://bit.ly/9611lt #plone #worldploneday #wpd2010 Apr 27, 2010 02:50 PM
@worldploneday: Colorado World Plone Day: This year's Colorado World Plone Day event will be held... http://bit.ly/dinZZn #plone #wpd2010 Apr 19, 2010 04:24 PM
 

browser view

Jun 22, 2010

Injecting Plone variables into javascript

by Mike Cullerton — last modified Jun 22, 2010 09:00 AM

I needed access to Plone variables (specifically portal_url) from within javascript. So, I created a browser view and python script that outputs the necessary variables, and registered the view in jsregistry.xml. This turned out to be a rather simple solution.

 

Step 1: Create a class to output the javascript

I created a file in src/my.product/my/product/browser called CommonUtils.py and added a class GlobalJS with a __call__ method that returns a string containing the javascript. __call__ sets the content-type, creates the string containing the variable, and returns the string.

class GlobalJS(BrowserView):
 
    def __call__(self,REQUEST,RESPONSE):
        RESPONSE.setHeader('Content-Type', 'application/javascript')
        js_string = "var portal_url = '%s';" % (self.context.portal_url())
        return js_string

 

Step 2: Create a browser view pointing to the class

In src/my.product/my/product/browser/configure.zcml, I added a browser view pointing to GlobalJS, gave it a name, and added a permission. Note that the name of the file containing GlobalJS is CommonUtils.py

<browser:view 
     for="*"
     name="global_js.js" 
     class=".CommonUtils.GlobalJS"
     permission="zope2.View"
     />

 

Step 3: Register the view in javascript registry

Here, I register the browser view in src/my.product/my/product/profiles/default/jsregistry.xml. I needed access to portal_url before jquery was loaded, so I added the insert-before property. Note that the id is the same as the name registered in the browser view.

<javascript 
    id="global_js.js"
    cacheable="True" compression="safe" cookable="True"
    enabled="True" expression=""  inline="True" insert-before="jquery.js"/>

 

Now, global_js.js is loaded on every page and I have access to portal_url from within javascript.

Hope this helps someone.

 
 
Copyright © 2003-2009 Core Software Group | 303/809-1001 | Fort Collins, Colorado | All rights reserved.