jquery plugins

15 views
Skip to first unread message

mdipierro

unread,
Feb 11, 2009, 12:26:13 PM2/11/09
to web2py Web Framework

mr.freeze

unread,
Feb 11, 2009, 2:31:14 PM2/11/09
to web2py Web Framework
Good stuff. That reminds me...I think a good addition to web2py would
be some kind of page/script manager (like t2's response.files on
steroids). Just thinking off the top of my head here but...

response.stylesheets (list rendered in the head of we2py_ajax.html)
response.pagescripts(list rendered in the head of we2py_ajax.html)
response.scripts(list rendered after the end of $(document).ready)

pagemanager.includestylesheet(path_to_static_css)
pagemanager.includescript(path_to_static_js)
pagemanager.addscript(your_script_snippet)

Each pagemanager method would check to see if the file/snippet already
exists in the corresponding response.[stylesheets,pagescripts,scripts]
before adding to prevent duplicates.

Then some jQuery helpers to abstract common selectors,manipulators and
effects so you could do:

pagemanager.addscript(jquery.getbyid('testid').fadein('slow'))
pagemanager.addscript(jquery.getbyclass('testclass').setattribute
('src','/images/hat.gif'))

Can you tell I'm bent on programming everything in Python?


On Feb 11, 11:26 am, mdipierro <mdipie...@cs.depaul.edu> wrote:
> do not miss these:
>
> http://devsnippets.com/reviews/using-jquery-to-style-design-elements-...

mdipierro

unread,
Feb 11, 2009, 2:40:31 PM2/11/09
to web2py Web Framework
Can you write the addscript function?

mr.freeze

unread,
Feb 11, 2009, 4:55:59 PM2/11/09
to web2py Web Framework
Sure. I think it would look something like this (in gluon/
clienttools.py):

class PageManager(object):
def __init__(self, response):
if not response.scripts: response.scripts = []
def addscript(self,script):
response.scripts.append(script)

Then in web2py_ajax.html as the last thing in the $(document).ready
function:

{{if response.scripts:}}
{{for s in response.scripts:}}
{{=s}}
{{pass}}
{{pass}}

Then in your db.py model:

from gluon.clienttools import PageManager
pagemanager=PageManager(response)

Then in your controller:

def index():
pagemanager.addscript("$('test').hide();")
response.flash=T('Welcome to web2py')
return dict(message=T('Hello World'))


Ideally, the clienttools module would be chocked full of jquery
helpers too :)

mr.freeze

unread,
Feb 12, 2009, 12:37:45 AM2/12/09
to web2py Web Framework
All together now... (gluon/clientutils.py)...

class PageManager(object):
def __init__(self, response):
self.response = response
self.response.scripts=[]
self.response.pagescripts=[]
self.response.stylesheets=[]
def addscript(self,script):
if not script in self.response.scripts:
self.response.scripts.append(script)
def addpagescript(self,pagescript):
if not pagescript in response.pagescripts:
response.pagescripts.append(pagescript)
def addstylesheet(self,stylesheet):
if not stylesheet in response.stylesheets:
response.stylesheets.append(stylesheet)
"""
The three methods below should not be used because
they require an instance variable in
the view making it non-generic. Here for testing.
"""
def includescripts
scripts = ''
for script in self.response.scripts:
scripts += script
return scripts
def includepagescripts
pagescripts = ''
for file in self.response.pagescripts:
pagescripts += SCRIPT(_src=file).xml()
return pagescripts
def includestylesheets
stylesheets = ''
for file in self.response.stylesheets:
stylesheets += LINK(_href=file,
_rel="stylesheet",
_type="text/css",
_charset="utf-8").xml()
return stylesheets

Now if I could just mimic jQuery's sweet chaining in Python...

mdipierro

unread,
Feb 12, 2009, 12:56:59 AM2/12/09
to web2py Web Framework
Try something like this:

class JQuery:
def __init__(self,name,attr=None,*args):
self.name=name
self.attr=attr
self.args=args
def __str__(self):
if not self.attr:
return "$('%s')" % self.name
import gluon.contrib.simplejson as json
args=', '.join([json.dumps(a) for a in self.args])
return "%s.%s(%s)" % (self.name, self.attr, args)
def __getattr__(self,attr):
def f(*args):
return JQuery(self,attr,*args)
return f

print JQuery('test').set(1,"",{}).get(45)

mdipierro

unread,
Feb 12, 2009, 1:20:00 AM2/12/09
to web2py Web Framework
Better and more powerful:

class JQuery:
def __init__(self,name,attr=None,*args):
self.name=name
self.attr=attr
self.args=args
def __str__(self):
import gluon.contrib.simplejson as json
def encode(obj):
if isinstance(obj,JQuery): return str(obj)
return json.dumps(obj)
if not self.attr:
return '$("%s")' % self.name
args=', '.join([encode(a) for a in self.args])
return '%s.%s(%s)' % (self.name, self.attr, args)
def __getattr__(self,attr):
def f(*args):
return JQuery(self,attr,*args)
return f

print JQuery('test').set(1,'',{},JQuery('#12').val()).get(45)

mdipierro

unread,
Feb 12, 2009, 1:33:11 AM2/12/09
to web2py Web Framework
from gluon.html import *

class JQuery:
def __init__(self,name,attr=None,*args):
self.name=name
self.attr=attr
self.args=args
def __str__(self):
import gluon.contrib.simplejson as json
def encode(obj):
if isinstance(obj,JQuery): return str(obj)
return json.dumps(obj)
if not self.attr:
return "$('%s')" % self.name
args=', '.join([encode(a) for a in self.args])
return '%s.%s(%s)' % (self.name, self.attr, args)
def xml(self):
raise AttributeError
def __getattr__(self,attr):
def f(*args):
return JQuery(self,attr,*args)
return f

### examples

>>> print JQuery('test').set(1,'',{},JQuery('#12').val()).get(45)

$('test').set(1, "", {}, $('#12').val()).get(45)

>>> print DIV(H1('clickme',_onclick=JQuery('#1').slideToggle()),P('bla '*10,_id=1))

<div><h1 onclick="$('#1').slideToggle()">clickme</h1><p id="1">bla bla
bla bla bla bla bla bla bla bla </p></div>



On Feb 11, 11:56 pm, mdipierro <mdipie...@cs.depaul.edu> wrote:

mr.freeze

unread,
Feb 12, 2009, 10:14:09 AM2/12/09
to web2py Web Framework
OMG, you just ported JQuery to Python in about 20 lines of code.
Speechless...

Would this work for more complicated jQuery like this?:
$("a")
.filter(".clickclass")
.click(function(){
alert("web2py rocks!");
})
.end()
.filter(".hideclass")
.click(function(){
$(this).hide();
return false;
})
.end();
> > > > > > >http://devsnippets.com/reviews/using-jquery-to-style-design-elements-...- Hide quoted text -
>
> - Show quoted text -

mdipierro

unread,
Feb 12, 2009, 10:28:41 AM2/12/09
to web2py Web Framework
Not quite. This works:

print JQuery("a").filter(".clickclass").click('xxx').end().filter
(".hideclass").click('yyy').end();

but here is no mechanism to pass a function yet....

Massimo
> > > > > > > >http://devsnippets.com/reviews/using-jquery-to-style-design-elements-...Hide quoted text -

mr.freeze

unread,
Feb 12, 2009, 11:50:08 AM2/12/09
to web2py Web Framework
Maybe a static method JQuery.function(body, *args) that just wraps a
JQuery object with function(args){body}? There's probably a better
way.
You would also need to add logic to handle the 'this' keyword and line
termination I think.
> > > > > > > > >http://devsnippets.com/reviews/using-jquery-to-style-design-elements-...quoted text -
>
> > > - Show quoted text -- Hide quoted text -

mdipierro

unread,
Feb 12, 2009, 12:18:53 PM2/12/09
to web2py Web Framework
This is not an easy one.
> > > > > > > > > >http://devsnippets.com/reviews/using-jquery-to-style-design-elements-...text -

mr.freeze

unread,
Feb 12, 2009, 5:06:15 PM2/12/09
to web2py Web Framework
This seems to be working now:

class PageManager(object):
def __init__(self, response):
self.response = response
self.response.scripts=[]
self.response.pagescripts=[]
self.response.stylesheets=[]
def addscript(self,script):
if not script in self.response.scripts:
self.response.scripts.append(script)
def addpagescript(self,pagescript):
if not pagescript in self.response.pagescripts:
self.response.pagescripts.append(pagescript)
def addstylesheet(self,stylesheet):
if not stylesheet in self.response.stylesheets:
self.response.stylesheets.append(stylesheet)
@staticmethod
def includescripts(scripts):
allscripts = scripts
outscript = ''
for script in allscripts:
outscript += XML(script).xml()
return outscript
@staticmethod
def includepagescripts(pagescripts):
allpagescripts = pagescripts
outscript = ''
for file in allpagescripts:
if file[-3:]=='.js':
outscript += SCRIPT(_src=file, _type="text/
javascript").xml()
return XML(outscript)
@staticmethod
def includestylesheets(stylesheets):
allstylesheets = stylesheets
outsheets = ''
for file in allstylesheets:
if file[-4:]=='.css':
outsheets += LINK(_href=file,
_rel="stylesheet",
_type="text/css",
_charset="utf-8").xml()
return XML(outsheets)

Just add in the appropriate sections of web2py_ajax.html(static
methods now):

{{if response.stylesheets:}}
{{=PageManager.includestylesheets(response.stylesheets)}}
{{pass}}

{{if response.pagescripts:}}
{{=PageManager.includepagescripts(response.pagescripts)}}
{{pass}}

{{if response.scripts:}}
{{=PageManager.includescripts(response.scripts)}}
{{pass}}

Then in a model:

from gluon.clientutils import PageManager
pagemanager=PageManager(response)

And in your controller you can do:

pagemanager.addscript("$('#test').slideToggle()")
pagemanager.addpagescript('/test/static/test.js')
pagemanager.addstylesheet('/test/static/test.css')
> > > > > > > > > > >http://devsnippets.com/reviews/using-jquery-to-style-design-elements-...-
Message has been deleted

mdipierro

unread,
Feb 13, 2009, 12:13:13 PM2/13/09
to web2py Web Framework
I like it. I would call Function JFunction instead.

Massion

On Feb 13, 11:01 am, "mr.freeze" <nfre...@gmail.com> wrote:
> What about this? '()' at the end of a JQuery statement terminates the
> line (;). Also added a simple Function wrapper class. Treats 'this' as
> a keyword.
>
> Mind you, there is a good chance that these helpers are more difficult
> that just writing jQuery code :)
>
> So this:
> print JQuery('#test').click(Function(JQuery("this").hide("slow")
> (),'event'))()
> print JQuery("p").bind("click",Function(JQuery("span").text("Click
> happened!")(),'e'))()
>
> Returns this:
> $('#test').click(function(event){$(this).hide("slow");});
> $('p').bind("click", function(e){$('span').text("Click happened!");});
>
> class JQuery:
>     def __init__(self,name,attr=None,*args):
>         self.name=name
>         self.attr=attr
>         self.args=args
>     def __str__(self):
>         import gluon.contrib.simplejson as json
>         def encode(obj):
>             if isinstance(obj,JQuery): return str(obj)
>             if isinstance(obj,Function): return str(obj)
>             return json.dumps(obj)
>         if not self.attr:
>             return ("$('%s')" % self.name).replace
> ("'this'","this")
>         args=', '.join([encode(a) for a in self.args])
>         return '%s.%s(%s)' % (self.name, self.attr, args)
>     def xml(self):
>         raise AttributeError
>     def __getattr__(self,attr):
>         def f(*args):
>             return JQuery(self,attr,*args)
>         return f
>     def __call__(self,*args):
>         if not args:
>             jq = str(JQuery(self))
>             jq = jq[3:]
>             jq = jq[:-2]
>             return jq + ";"
>
> class Function:
>     def __init__(self,body,*args):
>         self.body = body
>         self.args = args
>     def __str__(self):
>         args=', '.join([str(a) for a in self.args])
>         body=self.body
>         return "function(" + args + "){" + body + "}"
>
> On Feb 12, 11:18 am, mdipierro <mdipie...@cs.depaul.edu> wrote:
>
> > This is not an easy one.
>
> > On Feb 12, 10:50 am, "mr.freeze" <nfre...@gmail.com> wrote:
>
> > > Maybe a static methodJQuery.function(body, *args) that just wraps a
> > >JQueryobject with function(args){body}? There's probably a better
> > > way.
> > > You would also need to add logic to handle the 'this' keyword and line
> > > termination I think.
>
> > > On Feb 12, 9:28 am, mdipierro <mdipie...@cs.depaul.edu> wrote:
>
> > > > Not quite. This works:
>
> > > > printJQuery("a").filter(".clickclass").click('xxx').end().filter
> > > > (".hideclass").click('yyy').end();
>
> > > > but here is no mechanism to pass a function yet....
>
> > > > Massimo
>
> > > > On Feb 12, 9:14 am, "mr.freeze" <nfre...@gmail.com> wrote:
>
> > > > > OMG, you just portedJQueryto Python in about 20 lines of code.
> > > > > Speechless...
>
> > > > > Would this work for more complicatedjQuerylike this?:
> > > > > > >>> printJQuery('test').set(1,'',{},JQuery('#12').val()).get(45)
>
> > > > > > $('test').set(1, "", {}, $('#12').val()).get(45)
>
> > > > > > >>> print DIV(H1('clickme',_onclick=JQuery('#1').slideToggle()),P('bla '*10,_id=1))
>
> > > > > > <div><h1 onclick="$('#1').slideToggle()">clickme</h1><p id="1">bla bla
> > > > > > bla bla bla bla bla bla bla bla </p></div>
>
> > > > > > On Feb 11, 11:56 pm, mdipierro <mdipie...@cs.depaul.edu> wrote:
>
> > > > > > > Try something like this:
>
> > > > > > > classJQuery:
> > > > > > >    def __init__(self,name,attr=None,*args):
> > > > > > >        self.name=name
> > > > > > >        self.attr=attr
> > > > > > >        self.args=args
> > > > > > >    def __str__(self):
> > > > > > >        if not self.attr:
> > > > > > >            return "$('%s')" % self.name
> > > > > > >        import gluon.contrib.simplejson as json
> > > > > > >        args=', '.join([json.dumps(a) for a in self.args])
> > > > > > >        return "%s.%s(%s)" % (self.name, self.attr, args)
> > > > > > >    def __getattr__(self,attr):
> > > > > > >        def f(*args):
> > > > > > >            returnJQuery(self,attr,*args)
> > > > > > >        return f
>
> > > > > > > printJQuery('test').set(1,"",{}).get(45)
> > > > > > > > Now if I could just mimicjQuery'ssweet chaining in Python...
> ...
>
> read more »

mr.freeze

unread,
Feb 13, 2009, 12:15:29 PM2/13/09
to web2py Web Framework
Sorry, just removed the previous post because of an error. It doesn't
account for jQuery function calls like slideUp(). I'll repost once
fixed and rename Function to JFunction.
> ...
>
> read more »

mr.freeze

unread,
Feb 13, 2009, 12:26:26 PM2/13/09
to web2py Web Framework
Okay here it is:

>>>print JQuery("p").bind("click",JFunction(JQuery("this").slideUp()(),'e','o'))()
$('p').bind("click", function(e, o){$(this).slideUp();});
>>>print JQuery("this").slideUp()()
$(this).slideUp();

class JQuery:
def __init__(self,name,attr=None,*args):
self.name=name
self.attr=attr
self.args=args
def __str__(self):
import gluon.contrib.simplejson as json
def encode(obj):
if isinstance(obj,JQuery): return str(obj)
if isinstance(obj,JFunction): return str(obj)
return json.dumps(obj)
if not self.attr:
return ("$('%s')" % self.name).replace
("'this'","this")
args=', '.join([encode(a) for a in self.args])
return '%s.%s(%s)' % (self.name, self.attr, args)
def xml(self):
raise AttributeError
def __getattr__(self,attr):
def f(*args):
return JQuery(self,attr,*args)
return f
def __call__(self,*args):
if not args:
jq = str(JQuery(self))
jq = jq[3:]
jq = jq[:-2]
return jq + ";"

class JFunction:
def __init__(self,body,*args):
self.body = body
self.args = args
def __str__(self):
args=', '.join([str(a) for a in self.args])
body=self.body
return "function(" + args + "){" + body + "}"

> ...
>
> read more »

mr.freeze

unread,
Feb 13, 2009, 12:59:53 PM2/13/09
to web2py Web Framework
Massimo, do you think jQuery UI should be included with web2py?

BTW, with the PageManager class this works in a controller :)
pagemanager.addscript(JQuery("#footer").bind("click",JFunction(JQuery
("this").hide("slow")() + JQuery("this").show("slow")() ,'e'))())
> ...
>
> read more »

Markus Gritsch

unread,
Feb 13, 2009, 1:04:09 PM2/13/09
to web...@googlegroups.com
On Fri, Feb 13, 2009 at 6:59 PM, mr.freeze <nfr...@gmail.com> wrote:
>
> Massimo, do you think jQuery UI should be included with web2py?

According to http://jqueryui.com/download jQeuery UI complete is about
300 kB minified! Usually you build a custom UI file which only
contains the UI elements you need.

Markus

Reply all
Reply to author
Forward
0 new messages