Hi,
I defined a macro fro my own usage, starting from the example given in
http://creoleparserwiki.appspot.com/pages/DivMacroExample .
I modified slightly this example so that it scales better and,
hopefully, is easier to understand.
1- stick to a unique signature for every macro function: some_macro
(arg, body, isblock)
2- use a dictionary to select the macro to fire. This allows to get
rid of the successive elif that are prone to errors.
3- have an explicit default when no macro name is matched.
This gives something like:
from creoleparser import core, dialects
import genshi.builder as bldr
def float_div(arg, body, isblock):
if (not body or not isblock) :
return None
side = arg.strip()
if side not in ('left','right'):
return None
contents = text2html.generate(body)
fragment = bldr.tag.div(contents, style='float:'+side)
return fragment
def center_div(unused_arg, body, unused_isblock):
if (not body) :
return None
contents = text2html.generate(body)
fragment = bldr.tag.div(contents, CLASS='centered')
return fragment
def noop_macro(arg, body, isblock):
return None
macros = {'float' : float_div,
'center' : center_div,
}
def macro_dispatch(macro_name, arg,body,isblock):
return (macros.get(macro_name, noop_macro))(arg, body, isblock)
dialect = dialects.Creole10(
use_additions=True,
no_wiki_monospace=False,
macro_func=macro_dispatch
)
text2html = core.Parser(dialect)
With this pattern, it is quite easy to add new macros, without risking
regressions.
Cheers,
bruno