Search code examples
pluginstrac

Adding additional files to a Trac plugin


I am writing a plugin for Trac and want to put some additional files (e.g. css files) into my plugin.

I am using an egg-link to my source directory, and loading the plugin from there works, but the css file can not be found. So I thought maybe it searches relatively to the egg-link's path, but it didn't work neither.

Is it possible at all to add those files to the plugin, or do I have to put them in the script as strings? If it is possible, in which (relative) directory does it search for files when using an egg-link?


Solution

  • Static resources are made available using ITemplateProvider. Assume you have a typical directory structure like the following:

    • codereviewplugin
      • codereview
        • htdocs
          • css
            • codereview.css

    In one of your plugin's Component classes, which in this case it would likely be named CodeReviewModule in module web_ui.py, you'd implement ITemplateProvider with:

    def get_htdocs_dirs(self):
        from pkg_resources import resource_filename
        return [('codereview', resource_filename(__name__, 'htdocs')]
    

    You can then add the CSS file to a template using a call add_stylesheet('codereview/css/codereview.css').

    You also have to register the files in setup.py, otherwise it may work when installing the egg in editable mode (egg-link), but not in a normal egg installation:

    packages=['codereview'],
    package_data = {'codereview': ['htdocs/css/*.css'}
    

    There are many examples in the Trac core, such as Chrome.