Trac 0.10系向けのパンくず表示Macroを作りました!

会社でTracのWikiにパンくず表示するMacro欲しいよね〜って話が上がったので、さくっと作って見ました (*ノωノ)
如何せん Python 初めて & Trac Plugin 初めて なのでソースはお世辞にも綺麗じゃありませんが、目的の動作は果たしてるので公開してみます。


どういった動作をするかというと、TracのWikiにおいてページを

トップ/概要/詳細

みたいな感じでスラッシュ区切りの名前で管理している場合に、Wikiの好きなところに

[[TopicPath()]]

って書くと、その部分が

トップ > 概要 > 詳細

な感じのパンくずになります。
単純にパンくずが表示されてるだけじゃ意味ないんで、最終階層以外は自動でリンクが張られます。
この場合だと トップ と 概要 はリンクになってて 詳細 は単なるテキストになってる感じです。


と言うわけで、以下がソース (*ノωノ)

# -*- coding: utf-8 -*-
#
# TopicPath macro for Trac 0.10
#
# Author : Ruzia
# License: BSD

from trac.core import *
from trac.util.html import Markup
from trac.wiki.macros import WikiMacroBase
from StringIO import StringIO
from string import split

__all__ = ['TopicPathMacro']

class TopicPathMacro(WikiMacroBase):
    """
    Trac 0.10系用のパンくず表示用のMacroです。
    Wikiのページ名が
    
    /ほげ/ふが/ぴよ
    
    といった形で / によって区切られた名前がつけられている場合に、
    
    [[TopicPath()]]
    
    とWikiに記述すると
    
    ほげ > ふが > ぴよ
    
    といったパンくずを自動で表示します。
    その際、最終階層以外は自動でリンクが張られます。
    上記の例だと ほげ と ふが はリンクになります。
    """
    
    def render_macro(self, req, name, args):
        topic_path_html = StringIO()
       
        # get the refere page name
        current_page = req.path_info.startswith('/wiki/') and req.path_info[6:] or 'WikiStart'
       
        # format the topic path
        topic_tree = split(current_page, '/')
        link_tree = '' 
        for i in range(len(topic_tree) - 1):
            current_tree = topic_tree[i] 
            link_tree += current_tree + '/' 
            topic_path_html.write('<a href="%s">%s</a> &gt; ' % (req.href.wiki(link_tree), current_tree))
        else:
            topic_path_html.write('<strong>') 
            topic_path_html.write(topic_tree[len(topic_tree) - 1])
            topic_path_html.write('</strong>')
        
        return Markup(topic_path_html.getvalue())

使って見たいという方はソースを topicpath-trac-0.10.py として保存して



MacroBazaar – The Trac Project


の Installing a macro (new style macros) を参考にインストールして貰えば動くと思いますが、ご利用は自己責任にてお願いします!
なお、動作確認は 0.10.3 で行いました ( ´¬`)