views:

75

answers:

4

Hello,

I am using reStructured text to create some easy websites. So I have got a lot of *.rst files in which I want to add the Google Analytics code. But as far as I know it is not possible to add something like this?!

I am using rst2html to convert the files to html.

+2  A: 

I guess, you'd have to extend the docutils HTML Translator or Writer to include GA.

If possible, I'd recommend to abandon rst2html and plain docutils and use Sphinx instead. It is based on docutils, but far more powerful. Its HTML templates can easily be extended to include arbitrary HTML like script tags for Google Analytics.

lunaryorn
I will have a look at Sphinx. Thank you.
Mark
Sphinxis great for manuals, but for a website you might prefer rest2web http://www.voidspace.org.uk/python/rest2web/
Matti Pastell
+1  A: 

As a workaround to your problem, you could use a mass search/replace tool to add the Google Analytics code to the files after they have been through the translator. Just search for the </body> tag and replace it with <!--your tracking code--></body>.

I checked to see if you can include raw HTML in reStructuredText (and have it be untouched), but it doesn't seem possible...

alecwh
actually, you can add an invisible text in RST with `.. comment` syntax, it will be converted to comment on conversion to HTML
mykhal
I don't think you can include HTML markup... that's a comment.
alecwh
Good idea! Thanks. But I need something more comprehensive.
Mark
+1  A: 

You can insert html to rst files using the .. raw:: directive.

Matti Pastell
Unfortunately I need to add the HTML to the header. As far as I see this is not possible with the raw:: directive?!
Mark
In case of GA you don't need to add the code to the header, but right before the </body> tag, which means you place at the end of your .rst document.
Matti Pastell
Mark
+1  A: 

I've just discovered an easy way to add custom content to .rst files. All you need to do it to modify the template for html files.

Make a new template template.txt and the following contents to it (based on the default template):

%(head_prefix)s
%(head)s
<!--your tracking code-->
%(stylesheet)s
%(body_prefix)s
%(body_pre_docinfo)s
%(docinfo)s
%(body)s
%(body_suffix)s

The format is pretty self explanatory and its also a good way to remove the default CSS and specify a link to another one in the template etc.

Now you can use your custom template with the rst2html writer:

rst2html.py --template=template.txt document.rst
Matti Pastell