Pyramid/Pylons Framework - opinion on how am I using 'helpers' to accomplish certain tasks
Question
In pyramid, I have created a 'helpers' functionality similar to that in pylons.
one particular function in my helpers.py file is like this:
from pyramid.renderers import render_to_response
def createBlog():
## lots of code here ##
return render_to_response('blog.mako', {'xyz':xyz})
And then in my other applications I can import helpers and do something like the following in my templates:
${h.createBlog()}
which creates a blog on my page. But I am just wondering is this a good way of using helpers to create "module" style plugins that I can easily use anywhere in my projects. Or are there any flaws to this technique which I haven't really thought of yet?
Thanks!
Solution
It really depends on how much stuff you want to expose globally. Obviously anything you put into h
is available throughout the application, whereas you could return the createBlog
function just in the views you want it to be in. One little-known tidbit is that if you use class-based views, the actual class instance is available in the view as the view
global variable. For example:
class Foo(object):
def __init__(self, request):
self.request = request
def createBlog(self):
return render('blog.mako'. {})
@view_config(...)
def myview(self):
return {}
Now in your template you can call render your blog using ${view.createBlog()}
.