embedding youtube videos in trac wiki pages

while setting up a company internal trac wiki for a small project i wanted to include a link to a relevant youtube video and started looking for a YouTube trac macro — without finding one really.1 in typical top gear fashion i asked myself “how hard can it be” to write my own trac macro. turns out: not very.

so, here it is:

[python]
from datetime import datetime
# Note: since Trac 0.11, datetime objects are used internally

from genshi.builder import tag

from trac.util.datefmt import format_datetime, utc
from trac.wiki.macros import WikiMacroBase
from trac.util.html import Markup

import re

class YouTubeMacro(WikiMacroBase):
    '''Simple YouTube macro.

    Use as follows:

        [[YouTube(YOUTUBE-URL)]]
    '''

    revision = '0.2'
    url = 'http://xyzzyxyzzy.net'

    reYouTube = re.compile(r'http://.+/watch\?v=(?P<id>.+)$')

    def expand_macro(self, formatter, name, args):
        # parse: http://uk.youtube.com/watch?v=kJNDcurLP1w
        id = args
        match = YouTubeMacro.reYouTube.match(id)
        if match:
            id = match.group('id')

        return Markup('''<div class="tracyoutube">
   <object width="425" height="344">
       <param name="movie" value="http://www.youtube.com/v/%(id)s&hl=en&fs=1"></param>
       <param name="allowFullScreen" value="true"></param>
       <param name="allowscriptaccess" value="always"></param>
       <embed src="http://www.youtube.com/v/%(id)s&hl=en&fs=1" type="application/x-shockwave-flash"
              allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed>
   </object>
</div>''' % dict(id = id))
[/python]

cook for 5min, stir constantly, download to your trac’s plugin directory as YouTube.py and enjoy.


  1. the MovieMacro plugin looked like a good way of doing it, but apparently you need to install a special, embedded, flash player which i had no success with…