Saturday, June 19, 2010

Integrating hurry.resource into BFG

Back in PyCon APAC last week I was introduced to hurry.resource by its author, which is also one of the founder behind Grok, Martijn Faassen.

So, what does it do?.

Read Here

Lets go to the fun part

Setting Up

Assuming you are using one of the default BFG templates

First, enable ZCA. (or just do this in
config = Configurator(root_factory=get_root, settings=settings)

Do this little modification on the get_root function in
from repoze.bfg.interfaces import IRequest

def get_root(request):
return root

Add some component codes, name the file
from hurry.resource.interfaces import ICurrentNeededInclusions
from hurry.resource.interfaces import ILibraryUrl
from zope.interface import implements,implementer
from zope.component import getUtility,adapter
from hurry.resource import NeededInclusions
from repoze.bfg.interfaces import IRequest
from hurry.resource.core import Library

class NeededInclusion(object):

def __call__(self):
request = getUtility(IRequest)
if not hasattr(request,'needed'):
request.needed = NeededInclusions()
return request.needed

def LibraryUrl(library):
request = getUtility(IRequest)
return "%s/hurry/%s" % (request.application_url,

and hook them into ZCA by adding these into configure.zcml
<utility factory=".resource.NeededInclusion"/>
<adapter factory=".resource.LibraryUrl"/>

Adding into template
In your main template head section, add:
<tal:cond condition="getattr(request,'needed',None)">
<tal:res replace="structure request.needed.render()"/>

Using it

Lets take hurry.jquery for example:

First, register the static files, add these into configure.zcml

If you want to include Jquery js into your current view, just do this in the view code:
from hurry.jquery import jquery
def my_view(request):
return {'project':'helloworld'}

If you did the stuff above correctly, with luck , your view should have this in place of the tal block.

<script type="text/javascript" 

Custom Resource Libraries

You can create your own custom resource libraries and share/reuse it. To create your own resource, read the documentation of hurry.resource

Considering hurry.resource is also used in Grok and probably several other ZCA based frameworks, your resource library can also be reused on these frameworks with little to no modifications.

Credits to Martijn for this awesome component.

Happy hacking :D
Post a Comment
Locations of visitors to this page