| 34 | == Implementation == |
| 35 | |
| 36 | Here are 2 simple examples on how to create a Macro with [wiki:0.11 Trac 0.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. |
| 37 | |
| 38 | === Macro without arguments === |
| 39 | It should be saved as `TimeStamp.py` as Trac will use the module name as the Macro name |
| 40 | {{{ |
| 41 | from trac.core import * |
| 42 | from trac.wiki.macros import WikiMacroBase |
| 43 | from StringIO import StringIO |
| 44 | import time |
| 45 | |
| 46 | __all__ = ['TimestampMacro'] |
| 47 | |
| 48 | class TimestampMacro(WikiMacroBase): |
| 49 | """ |
| 50 | Macro for inserting timestamp |
| 51 | |
| 52 | {{{ |
| 53 | [[Timestamp]] |
| 54 | }}} |
| 55 | """ |
| 56 | def expand_macro(self, formatter, name, args): |
| 57 | buf = StringIO() |
| 58 | t = time.localtime() |
| 59 | buf = "<b>%s</b>" % time.strftime('%c', t) |
| 60 | return buf |
| 61 | }}} |
| 62 | |
| 63 | === Macro with arguments === |
| 64 | It should be saved as `HelloWorld.py` as Trac will use the module name as the Macro name |
| 65 | {{{ |
| 66 | """Example macro.""" |
| 67 | from trac.core import * |
| 68 | from trac.wiki.macros import WikiMacroBase |
| 69 | from trac.util import escape |
| 70 | |
| 71 | __all__ = ['HelloWorldMacro'] |
| 72 | |
| 73 | class HelloWorldMacro(WikiMacroBase): |
| 74 | """ |
| 75 | Demo macro for a greeting with an argument. |
| 76 | |
| 77 | {{{ |
| 78 | [[HelloWorld(args)]] |
| 79 | }}} |
| 80 | |
| 81 | """ |
| 82 | def expand_macro(self, formatter, name, args): |
| 83 | # args will be `None` if the macro is called without parenthesis. |
| 84 | txt = args or 'No arguments' |
| 85 | |
| 86 | # then, as `txt` comes from the user, it's important to guard against |
| 87 | # the possibility to inject malicious HTML/Javascript, by using `escape()`: |
| 88 | return 'Hello World, args = ' + escape(txt) |
| 89 | }}} |
| 90 | |
| 91 | |