Edgewall Software

Ticket #7728: hrefexample.py

File hrefexample.py, 1.3 KB (added by martin@…, 8 years ago)

Example macro with clean href extraction code

Line 
1""" Copyright (c) 2008 Martin Scharrer <martin@scharrer-online.de>
2 v0.1 - Oct 2008
3 This is Free Software under the GPL v3!
4"""
5from trac.core import *
6from trac.wiki.api import parse_args
7from trac.wiki.macros import WikiMacroBase
8from genshi.builder import Element
9from trac.wiki.formatter import extract_link
10from StringIO import StringIO
11
12
13class HrefExtractionExampleMacro(WikiMacroBase):
14 """ Provides the macro
15 """
16
17 def expand_macro(self, formatter, name, content):
18 args, kwargs = parse_args(content)
19 traclink = args[0]
20
21 link = extract_link(self.env, formatter.context, traclink)
22 if isinstance(link, Element):
23 href = link.attrib.get('href')
24 else:
25 href = traclink
26
27 if href == None:
28 raise TracError('Link "%s" invalid!' % traclink)
29
30 # Raw href is needed:
31 if href.startswith('/browser/'):
32 if href.find('?') == -1:
33 href = '%s?format=raw' % href
34 else:
35 href = '%s&format=raw' % href
36 elif href.startswith('/attachment/'):
37 href = href.replace('/attachment/','/raw-attachment/', 1)
38
39 out = StringIO()
40 # Test output:
41 out.write( '||%s| => |%s||<br />\n' % (link,href) );
42 return out.getvalue()
43