wiki:EggCookingTutorial/AdvancedEggCooking2

Version 1 (modified by Jani Tiainen, 19 years ago) (diff)

Initial article text

Advanced egg boiling part 2

Now you have pretty neat plugin already but let's add final twist and serve some static content like stylesheet and image.

Important thing to check

First step is to ensure that your trac.ini doesn't have htdocs_location set otherwise Trac can't serve static data.

More directories

Since we don't have enough directories in our simple plugin let's make few more:

./helloworld-plugin/helloworld/htdocs/
./helloworld-plugin/helloworld/htdocs/css/
./helloworld-plugin/helloworld/htdocs/images/

Style is everything

We want to use our own stylesheet to give some color to our fine content. For that we need cascaded stylesheet.

Create helloworld.css in ./helloworld-plugin/helloworld/htdocs/css/:

div.helloworld h1 {
	color: red;
}

Image tells more than thousand words

Images are always nice.

Put small image named helloworld.jpg in ./helloworld-plugin/helloworld/htdocs/images/.

Note: Since it's not practical to show jpg contents here you should find one image by yourself somewhere.

Egg grows

Even natural eggs doesn't grow Python eggs does.

Modify setup.py to include our static data:

from setuptools import setup

PACKAGE = 'TracHelloworld'
VERSION = '0.1'

setup(name=PACKAGE, version=VERSION, packages=['helloworld'],
      package_data={'helloworld' : ['htdocs/css/*.css', 'htdocs/images/*.jpg', 
                                    'templates/*.cs' ]})

Tell it to Trac too

Trac doesn't know where our fine stylesheet and image is located. So you have to tell it to Trac.

Add static data path to end of our plugin in file helloworld.py:

    def get_htdocs_dir(self):
        """
        Return the absolute path of a directory containing additional
        static resources (such as images, style sheets, etc).
        """
        from pkg_resources import resource_filename
        return resource_filename(__name__, 'htdocs')	

Remember to load stylesheet

To make Trac to load our stylesheet you need to modify process_request method starting from line 23 to following:

    def process_request(self, req):
        add_stylesheet(req, 'css/helloworld.css')
        return 'helloworld.cs', None

Back to images

We need to add our image to template to see it.

Our new helloworld.cs:

<?cs include "header.cs" ?>
<?cs include "macros.cs" ?>

<div id="content" class="helloworld">
 <h1>Hello world!</h1>
 <img src="<?cs var:htdocs_location ?>images/helloworld.jpg">
</div>

<?cs include "footer.cs" ?>

Compilation and deployment

Now you should be familiar with both, so make an egg and deploy it.

Click and see... Hello world! with your pretty own image.

Aftermath

Now you have successfully completed nice simple plugin that uses it's own template and servers some static data.

Attachments (2)

Download all attachments as: .zip