Changes between Version 1 and Version 2 of WikiMacros
- Timestamp:
- 11/04/11 12:44:56 (19 months ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
WikiMacros
v1 v2 1 = Macros na Wiki = 2 [[TracGuideToc]] 3 Macros no Trac são plugins que extendem a funcionalidade do Trac com 'funções' escritas em Python.Um macro insere dinamicamente um dado HTML em qualquer contexto suportado pelo WikiFormatting. 1 = Trac Macros = 4 2 5 Outro tipo de macro são os WikiProcessors. Eles tipicamente são alternativas a formatações de alto nível e representações de grandes blocos de informação (como um código-fonte em destaque). 3 [[PageOutline]] 6 4 7 Veja também: WikiProcessors.5 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. 8 6 9 == Usando Macros == 10 As chamadas de macros são atreladas a ''[]''. Como nas funções do Python, macros também podem ter argumentos,usando-se uma lista separada por vírgulas dentro de parênteses. 7 Another kind of macros are WikiProcessors. They typically deal with alternate markup formats and representation of larger blocks of information (like source code highlighting). 11 8 12 === Exemplos === 9 == Using Macros == 10 Macro calls are enclosed in two ''square brackets''. Like Python functions, macros can also have arguments, a comma separated list within parentheses. 11 12 Trac macros can also be written as TracPlugins. This gives them some capabilities that macros do not have, such as being able to directly access the HTTP request. 13 14 === Example === 15 16 A list of 3 most recently changed wiki pages starting with 'Trac': 13 17 14 18 {{{ 15 [[ Timestamp]]19 [[RecentChanges(Trac,3)]] 16 20 }}} 17 Mostrará:18 [[Timestamp]]19 21 20 {{{ 21 [[HelloWorld(Testing)]] 22 }}} 23 Mostrará: 24 [[HelloWorld(Testing)]] 22 Display: 23 [[RecentChanges(Trac,3)]] 24 25 == Available Macros == 26 27 ''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].'' 28 29 [[MacroList]] 30 31 == Macros from around the world == 32 33 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. 34 35 == Developing Custom Macros == 36 Macros, like Trac itself, are written in the [http://python.org/ Python programming language]. 37 38 For more information about developing macros, see the [trac:TracDev development resources] on the main project site. 25 39 26 40 27 == Macros Disponiníveis == 28 Macros ainda são novidades e a lista de macros disponíveis (e distribuidos) não é muito extensa. Em futuras versões do Trac, nós esperamos construir uma biblioteca bem útil de macros e vamos agradecidamente incluir contribuições de macros (veja abaixo). 41 == Implementation == 29 42 30 * '''!HelloWorld''' -- Um exemplo de macro, muito útil para se aprender a escrever macros. 31 * '''Timestamp''' -- Insere a data e a hora atual. 43 Here are 2 simple examples showing how to create a Macro with Trac 0.11. 32 44 45 Also, have a look at [trac:source:tags/trac-0.11/sample-plugins/Timestamp.py Timestamp.py] for an example that shows the difference between old style and new style macros and at the [trac:source:tags/trac-0.11/wiki-macros/README macros/README] which provides a little more insight about the transition. 33 46 34 ---- 47 === Macro without arguments === 48 It should be saved as `TimeStamp.py` (in the TracEnvironment's `plugins/` directory) as Trac will use the module name as the Macro name. 49 {{{ 50 #!python 51 from datetime import datetime 52 # Note: since Trac 0.11, datetime objects are used internally 35 53 54 from genshi.builder import tag 36 55 37 == Macros através do mundo == 38 A página do [http://projects.edgewall.com/trac/ Projeto Trac] tem um seção dedicada para macros contribuídos pelos usuários [http://projects.edgewall.com/trac/wiki/MacroBazaar MacroBazaar]. Se você está procurando por novos macros ou escreveu alguns novos , não hesite em adicioná-lo a página wiki do http://projects.edgewall.com/trac/wiki/MacroBazaar MacroBazaar]. 56 from trac.util.datefmt import format_datetime, utc 57 from trac.wiki.macros import WikiMacroBase 39 58 40 http://projects.edgewall.com/trac/wiki/MacroBazaar 59 class TimeStampMacro(WikiMacroBase): 60 """Inserts the current time (in seconds) into the wiki page.""" 41 61 62 revision = "$Rev$" 63 url = "$URL$" 42 64 43 ---- 44 45 46 == Desenvolvendo Novos Macros == 47 Macros, como o Trac, são escritos usando-se [http://www.python.org/ Linguagem de Programação Python]. Eles são compostos de simples módulos, identificados pelo nome do arquivo e que devem conter um único ''ponto de entrada'' nas funções.o Trac irá mostrar o dado inserido dentro do HTML quando o mesmo for chamado. 48 49 50 É muito fácil aprender a partir de um exemplo: 51 {{{ 52 # MeuMacro.py -- O macro mais simple do mundo 53 def execute(hdf, args, env): 54 return "Oi mundo chamado com os argumentos: %s" % args 65 def expand_macro(self, formatter, name, args): 66 t = datetime.now(utc) 67 return tag.b(format_datetime(t, '%c')) 55 68 }}} 56 69 57 === Tópicos Avançados: Macros embutidos em Templates === 58 Para usuários avançados, macros também pode renderizar a saída em HDF, para serem renderizados para HTML usando-se templates clearsilver - como na maioria das saídas do Trac. Em resumo, isto permite mais genéricos e bem desenvolvidos macros avançados. 70 === Macro with arguments === 71 It should be saved as `HelloWorld.py` (in the TracEnvironment's `plugins/` directory) as Trac will use the module name as the Macro name. 72 {{{ 73 #!python 74 from trac.wiki.macros import WikiMacroBase 59 75 60 Macros ganham acesso direto a principal árvore do HDF e podem manipulá-las livremente. 76 class HelloWorldMacro(WikiMacroBase): 77 """Simple HelloWorld macro. 61 78 62 Exemplo: 63 {{{ 64 def execute(hdf, args, env): 65 # o hdf atual só é setado quando o macro é chamado 66 # de uma página wiki 67 if hdf: 68 hdf.setValue('wiki.macro.greeting', 'Olá Mundo') 69 70 # os argumentos serão nulos se o macro for chamado sem parênteses. 71 args = args or 'Sem argumentos' 72 return 'Olá mundo, args = ' + args 79 Note that the name of the class is meaningful: 80 - it must end with "Macro" 81 - what comes before "Macro" ends up being the macro name 82 83 The documentation of the class (i.e. what you're reading) 84 will become the documentation of the macro, as shown by 85 the !MacroList macro (usually used in the WikiMacros page). 86 """ 87 88 revision = "$Rev$" 89 url = "$URL$" 90 91 def expand_macro(self, formatter, name, args): 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 `args` is the text enclosed in parenthesis at the call of the macro. 97 Note that if there are ''no'' parenthesis (like in, e.g. 98 [[HelloWorld]]), then `args` is `None`. 99 """ 100 return 'Hello World, args = ' + unicode(args) 101 102 # Note that there's no need to HTML escape the returned data, 103 # as the template engine (Genshi) will do it for us. 73 104 }}} 74 105 75 106 76 Você também pode usar o objeto ambiente (env) para acessar um dado de configuração. 107 === {{{expand_macro}}} details === 108 {{{expand_macro}}} should return either a simple Python string which will be interpreted as HTML, or preferably a Markup object (use {{{from trac.util.html import Markup}}}). {{{Markup(string)}}} just annotates the string so the renderer will render the HTML string as-is with no escaping. You will also need to import Formatter using {{{from trac.wiki import Formatter}}}. 77 109 110 If your macro creates wiki markup instead of HTML, you can convert it to HTML like this: 78 111 79 Exemplo.80 112 {{{ 81 def execute(hdf, txt, env): 82 return env.get_config('trac', 'repository_dir') 113 #!python 114 text = "whatever wiki markup you want, even containing other macros" 115 # Convert Wiki markup to HTML, new style 116 out = StringIO() 117 Formatter(self.env, formatter.context).format(text, out) 118 return Markup(out.getvalue()) 83 119 }}} 84 85 86 ----87 Veja também: WikiProcessors, WikiFormatting, TracGuide
