| 1 | '''Beware: I'm by no means an expert and just quickly collected Information that seems right. The sources for these Macros are at: ticket:5274''' |
| 2 | |
| 3 | * ticket:5274/HelloWorld.py |
| 4 | * ticket:5274/Timestamp.py |
| 5 | |
| 6 | = Implementation Changes = |
| 7 | |
| 8 | [wiki:Trac0.11 Trac0.11] has significant changes for it's Macro processing and Implementation. |
| 9 | |
| 10 | Here are 2 simple examples on how to create a Macro with [wiki:Trac0.11 Trac0.11] have a look at source:trunk/sample-plugins/Timestamp.py for an example that shows the difference between old style and new style macros and also source:trunk/wiki-macros/README which Provides a little more insight. |
| 11 | |
| 12 | == Macro without arguments == |
| 13 | It should be saved as `TimeStamp.py` as Trac will use the module name as the Macro name |
| 14 | {{{ |
| 15 | from trac.core import * |
| 16 | from trac.wiki.macros import WikiMacroBase |
| 17 | from StringIO import StringIO |
| 18 | import time |
| 19 | |
| 20 | __all__ = ['TimestampMacro'] |
| 21 | |
| 22 | class TimestampMacro(WikiMacroBase): |
| 23 | """ |
| 24 | Macro for inserting timestamp |
| 25 | |
| 26 | {{{ |
| 27 | [[Timestamp]] |
| 28 | }}} |
| 29 | """ |
| 30 | def expand_macro(self, formatter, name, args): |
| 31 | buf = StringIO() |
| 32 | t = time.localtime() |
| 33 | buf = "<b>%s</b>" % time.strftime('%c', t) |
| 34 | return buf |
| 35 | }}} |
| 36 | |
| 37 | == Macro with arguments == |
| 38 | It should be saved as `HelloWorld.py` as Trac will use the module name as the Macro name |
| 39 | {{{ |
| 40 | """Example macro.""" |
| 41 | from trac.core import * |
| 42 | from trac.wiki.macros import WikiMacroBase |
| 43 | from trac.util import escape |
| 44 | |
| 45 | __all__ = ['HelloWorldMacro'] |
| 46 | |
| 47 | class HelloWorldMacro(WikiMacroBase): |
| 48 | """ |
| 49 | Demo macro for a greeting with an argument. |
| 50 | |
| 51 | {{{ |
| 52 | [[HelloWorld(args)]] |
| 53 | }}} |
| 54 | |
| 55 | """ |
| 56 | def expand_macro(self, formatter, name, args): |
| 57 | # args will be `None` if the macro is called without parenthesis. |
| 58 | txt = args or 'No arguments' |
| 59 | |
| 60 | # then, as `txt` comes from the user, it's important to guard against |
| 61 | # the possibility to inject malicious HTML/Javascript, by using `escape()`: |
| 62 | return 'Hello World, args = ' + escape(txt) |
| 63 | }}} |