Changes between Version 1 and Version 2 of WikiMacros


Ignore:
Timestamp:
07/10/20 13:09:46 (2 years ago)
Author:
trac
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • WikiMacros

    v1 v2  
    1 =  Wiki Macros =
    2 Trac macros are plugins to extend the Trac engine with custom 'functions' written in Python. A macro inserts dynamic HTML data in any context supporting WikiFormatting.
     1= Trac Macros
    32
    4 Another kind of macros are WikiProcessors. They typically deal with alternate markup formats and representation of larger blocks of information (like source code highlighting).
     3[[PageOutline(2-5,Contents,pullout)]]
    54
    6 == Using Macros ==
    7 Macro calls are enclosed in two ''square brackets''. Like Python functions, macros can also have arguments, a comma separated list within parentheses.
     5'''Trac macros''' extend Trac with custom functionality. Macros are a special type of plugin and are written in Python. A macro generates HTML in any context supporting WikiFormatting.
    86
    9 === Examples ===
     7The macro syntax is `[[macro-name(optional-arguments)]]`.
     8
     9'''WikiProcessors''' are another kind of macro, commonly used for source code highlighting using a processor like `!#python` or `!#apache`:
    1010
    1111{{{
    12  [[Timestamp]]
     12{{{#!wiki-processor-name
     13...
    1314}}}
    14 Display:
    15  [[Timestamp]]
     15}}}
    1616
    17 {{{
    18  [[HelloWorld(Testing)]]
     17== Using Macros
     18
     19Macro calls are enclosed in double-square brackets `[[..]]`. Like Python functions macros can have arguments, which take the form of a comma separated list within parentheses `[[..(,)]]`. A common macro used is a list of the 3 most recent changes to a wiki page, or here, for example, all wiki pages starting with 'Trac':
     20
     21||= Wiki Markup =||= Display =||
     22{{{#!td
     23  {{{
     24  [[RecentChanges(Trac,3)]]
     25  }}}
    1926}}}
    20 Display:
    21  [[HelloWorld(Testing)]]
     27{{{#!td style="padding-left: 2em;"
     28[[RecentChanges(Trac,3)]]
     29}}}
    2230
    23 == Available Macros ==
     31=== Getting Detailed Help
    2432
    25 ''Note that the following list will only contain the macro documentation if you've not enabled `-OO` optimizations, or not set the `PythonOptimize` option for [wiki:TracModPython mod_python].''
     33The list of available macros and the full help can be obtained using the !MacroList macro, see [#AvailableMacros below].
     34
     35A brief list can be obtained via `[[MacroList(*)]]` or `[[?]]`.
     36
     37Detailed help on a specific macro can be obtained by passing it as an argument to !MacroList, e.g. `[[MacroList(MacroList)]]`, or more conveniently, by appending a question mark (`?`) to the macro's name, like in `[[MacroList?]]`.
     38
     39== Available Macros
    2640
    2741[[MacroList]]
    2842
    29 == Macros from around the world ==
     43== Contributed macros
    3044
    31 The [http://trac-hacks.org/ Trac Hacks] site provides a wide collection of macros and other Trac [TracPlugins plugins] contributed by the Trac community. If you're looking for new macros, or have written one that you'd like to share with the world, please don't hesitate to visit that site.
     45The [https://trac-hacks.org/ Trac Hacks] site provides a large collection of macros and other Trac [TracPlugins plugins] contributed by the Trac community. If you are looking for new macros, or have written one that you would like to share, please visit that site.
    3246
    33 == Developing Custom Macros ==
    34 Macros, like Trac itself, are written in the [http://www.python.org/ Python programming language]. They are very simple modules, identified by the filename and should contain a single `execute()` function. Trac will display the returned data inserted into the HTML representation of the Wiki page where the macro is called.
     47== Developing Custom Macros
    3548
    36 It's easiest to learn from an example:
    37 {{{
    38 #!python
    39 # MyMacro.py -- The world's simplest macro
     49Macros, like Trac itself, are written in the [https://python.org/ Python programming language] and are a type of [TracPlugins plugin].
    4050
    41 def execute(hdf, args, env):
    42     return "Hello World called with args: %s" % args
     51Here are 2 simple examples showing how to create a Macro. For more information about developing macros, see the [trac:TracDev development resources] and [trac:browser:branches/1.4-stable/sample-plugins sample-plugins].
     52
     53=== Macro without arguments
     54
     55To test the following code, copy it to `timestamp_sample.py` in the TracEnvironment's `plugins/` directory.
     56
     57{{{#!python
     58from trac.util.datefmt import datetime_now, format_datetime, utc
     59from trac.util.html import tag
     60from trac.wiki.macros import WikiMacroBase
     61
     62class TimestampMacro(WikiMacroBase):
     63    _description = "Inserts the current time (in seconds) into the wiki page."
     64
     65    def expand_macro(self, formatter, name, content, args=None):
     66        t = datetime_now(utc)
     67        return tag.strong(format_datetime(t, '%c'))
    4368}}}
    4469
    45 You can also use the environment (`env`) object, for example to access configuration data and the database, for example:
    46 {{{
    47 #!python
    48 def execute(hdf, txt, env):
    49     return env.config.get('trac', 'repository_dir')
     70=== Macro with arguments
     71
     72To test the following code, copy it to `helloworld_sample.py` in the TracEnvironment's `plugins/` directory.
     73
     74{{{#!python
     75from trac.util.translation import cleandoc_
     76from trac.wiki.macros import WikiMacroBase
     77
     78class HelloWorldMacro(WikiMacroBase):
     79    _description = cleandoc_(
     80    """Simple HelloWorld macro.
     81
     82    Note that the name of the class is meaningful:
     83     - it must end with "Macro"
     84     - what comes before "Macro" ends up being the macro name
     85
     86    The documentation of the class (i.e. what you're reading)
     87    will become the documentation of the macro, as shown by
     88    the !MacroList macro (usually used in the WikiMacros page).
     89    """)
     90
     91    def expand_macro(self, formatter, name, content, args=None):
     92        """Return some output that will be displayed in the Wiki content.
     93
     94        `name` is the actual name of the macro (no surprise, here it'll be
     95        `'HelloWorld'`),
     96        `content` is the text enclosed in parenthesis at the call of the
     97          macro. Note that if there are ''no'' parenthesis (like in, e.g.
     98          [[HelloWorld]]), then `content` is `None`.
     99        `args` will contain a dictionary of arguments when called using the
     100          Wiki processor syntax and will be `None` if called using the
     101          macro syntax.
     102        """
     103        return 'Hello World, content = ' + unicode(content)
    50104}}}
    51105
    52 Note that since version 0.9, wiki macros can also be written as TracPlugins. This gives them some capabilities that “classic” macros do not have, such as being able to directly access the HTTP request.
     106Note that `expand_macro` optionally takes a 4^th^ parameter ''`args`''. When the macro is called as a [WikiProcessors WikiProcessor], it is also possible to pass `key=value` [WikiProcessors#UsingProcessors processor parameters]. If given, those are stored in a dictionary and passed in this extra `args` parameter. When called as a macro, `args` is `None`.
    53107
    54 For more information about developing macros, see the [http://projects.edgewall.com/trac/wiki/TracDev development resources] on the main project site.
     108For example, when writing:
     109{{{
     110{{{#!HelloWorld style="polite" -silent verbose
     111<Hello World!>
     112}}}
    55113
    56 ----
    57 See also:  WikiProcessors, WikiFormatting, TracGuide
     114{{{#!HelloWorld
     115<Hello World!>
     116}}}
     117
     118[[HelloWorld(<Hello World!>)]]
     119}}}
     120
     121One should get:
     122{{{
     123Hello World, text = <Hello World!>, args = {'style': u'polite', 'silent': False, 'verbose': True}
     124Hello World, text = <Hello World!>, args = {}
     125Hello World, text = <Hello World!>, args = None
     126}}}
     127
     128Note that the return value of `expand_macro` is '''not''' HTML escaped. Depending on the expected result, you should escape it yourself (using `return Markup.escape(result)`), or if this is indeed HTML, wrap it in a Markup object: `return Markup(result)` (`from trac.util.html import Markup`).
     129
     130You can also recursively use a wiki formatter to process the `content` as wiki markup:
     131
     132{{{#!python
     133from trac.wiki.formatter import format_to_html
     134from trac.wiki.macros import WikiMacroBase
     135
     136class HelloWorldMacro(WikiMacroBase):
     137    def expand_macro(self, formatter, name, content, args):
     138        content = "any '''wiki''' markup you want, even containing other macros"
     139        # Convert Wiki markup to HTML
     140        return format_to_html(self.env, formatter.context, content)
     141}}}