Something that you usually need to do when providing a library or a reusable wsgi application is installing static data with the library itself.
This can be quickly performed by adding something like
package_data = {”:[‘*.html’, ‘*.js’, ‘*.css’, ‘*.png’]}
to your setup.py
But then how can we let our turbogears application serve that?
- For html files (genshi templates) the solution is quite simple, you can just expose them by using @expose(‘librarypackage.templatesdir.template’). For example supposing we are installing libcool with its templates in libcool/templates you can do @expose(‘libcool.templates.index’)
- For js and css files you can add them to your pages by creating a tw.api.JSLink or tw.api.CSSLink object. Just create inside your library something like: cool_js = tw.api.JSLink(modname = __name__, filename = ‘static/cool.js’) and then place in the controller exposing the view where you want to use that js file cool_js.inject()
- Exposing images can be more complex, you have to declare a widget which will render the img tag by using ToscaWidgets resources exposure.
class IconLink(tw.api.Link): """ A link to an icon. """ template = """<img src="$link" alt="$alt" />""" params = dict(alt="Alternative text when not displaying the image") def __init__(self, *args, **kw): super(IconLink, self).__init__(*args, **kw) self.alt = kw.get('alt')
then you can create one IconLink for each icon in your library with something like: parent = IconLink(modname=__name__, filename=’static/icons/parent.png’, alt=’Up’) and inside your views you can place the icon by doing ${parent.display()} . This will add the image by exposing it from inside the static directory of your library package. Remember that you need to add an __init__.py inside the static directory and its subdirectory if you want setuptools to correctly install the static files.