Version 87.2 by Vincent Massol on 2013/09/11

Show last authors
1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc/}}
3 {{/box}}
4
5 Wiki macros allow macro authors to develop reusable and distributable macro modules. There is no java code involved; hence no compiling or packaging. The macro author simply needs to create a wiki page according to a particular specification and that's all!
6
7 = Macro Visibility and Rights =
8
9 There are 3 levels of visibility for a macro:
10
11 * farm (if we're in a multiwiki environment), meaning that the macro will be available in all the wikis of the farm
12 * wiki, which means that the macro will be available in its wiki
13 * user, which means that the macro will only be available to the user which is its author
14
15 The rights required to create macros are different depending on the visibility we want for our macro:
16
17 * the macro author needs to have **programming** rights for a macro available in the whole **farm**
18 * the macro author needs to have **admin** rights for a macro available in its **wiki**
19 * no special rights besides the obvious right to edit the page are needed for a macro available only to its author.
20
21 == Using protected API in wiki macros ==
22
23 Also, if the macro needs to use [[protected API>>Scripting||anchor="HXWikiCoreAccess"]], the author of the macro will need to have programming rights. Note that the macro will always be executed with the rights of its author, and not with the rights of the author of the calling document (the document using the macro). Specifically, if the macro uses protected API, only the macro author needs to have programming rights, not all the authors of the documents that call this macro.
24
25 = Hello Macro =
26
27 We are going to start with a very simple xwiki/2.0 wiki macro which prints a greeting message to the document content. It isn't a very useful macro but the idea is to get you familiarised with the wiki macro creation process.
28
29 == Definition ==
30
31 Wiki macros are defined using objects of type ##XWiki.WikiMacroClass##. You define a wiki macro by creating a new wiki page and attaching to it an object of type ##XWiki.WikiMacroClass##. This class contains the following fields:
32
33 * Macro id: Id of the macro to be used by users when invoking your macro from wiki code
34 * Macro name: Name of the macro to be displayed on the wysiwyg editor
35 * Macro description: A short description of the macro to be displayed on the WYSIWYG editor
36 * Default category: Default category under which this macro should be listed
37 * Supports inline mode: Whether the macro can be used in an inline context or not
38 * Macro content type: Whether this macro should support a body or not
39 * Content description: A short description about the macro's content to be displayed on the WYSIWYG editor
40 * Macro code: The actual wiki code that will be evaluated when the macro is executed, can be any xwiki content (should be in the same syntax as the document)
41
42 Now we can define our hello macro as shown below:
43
44 [[image:macro1.png]]
45
46 == Invocation ==
47
48 A wiki macro can be invoked just like any other macro is invoked. Since we are writing a xwiki/2.0 wiki macro, we can invoke our **hello macro** as below:
49
50 {{code}}
51 {{hello/}}
52 {{/code}}
53
54 And if you view the result it would say "Hello World!" (of course).
55
56 == Content ==
57
58 If macro content is used, it can be shown by executing the following velocity code in the macro body:
59
60 {{code language="none"}}
61 {{velocity}}$xcontext.macro.content{{/velocity}}
62 {{/code}}
63
64 For more details, see the [[Scripting Tips section below>>||anchor="HScriptingTips"]].
65
66 == Parameters ==
67
68 Introducing a parameter to a wiki macro is pretty straight forward; you simply need to add an object of type ##XWiki.WikiMacroParameterClass## into your wiki macro document (one object per parameter). This class contains several fields that allow you to define your parameter clearly:
69
70 * Parameter name: Name of the parameter, users will refer this name when invoking your macro with parameters
71 * Parameter description: A short description of the parameter, this description will be made available on the WYSIWYG editor
72 * Parameter mandatory: Indicates if this particular parameter is mandatory, wiki macro will fail to execute if a mandatory parameter is missing
73
74 Now we're going to extend our **hello macro** with a parameter. We will introduce a parameter named //greetUser// that will indicate if the greeting message should be tailored for the current user viewing the page. The definition of the parameter is shown below:
75
76 [[image:macro3.png]]
77
78 A macro parameter defined this way can be accessed from any scripting language within the macro code. For example, we are going to utilize our //greetUser// parameter within **hello macro** as shown below:
79
80 [[image:macro4.png]]
81
82 As you might have realized already, direct binding of parameters is not supported at the moment. That is, you cannot access //greetUser// parameter with **$greetUser**. Instead you must use **$xcontext.macro.params.greetUser**. We plan to introduce some form of direct parameter binding in near future.
83
84 Finally, we can test our new version of **hello macro** with the following invocation:
85
86 {{code language="none"}}
87 {{hello greetUser="true"/}}
88 {{/code}}
89
90 = WYSIWYG Access =
91
92 A wiki macros is treated just like any other rendering macro in the system. As such, the moment you save your wiki macro it will be available to the users through the WYSIWYG editor's **Insert Macro** dialog box:
93
94 [[image:macro2.png]]
95
96 [[image:macro5.png]]
97
98 == Special code for WYSIWYG edit mode ==
99
100 Even in edit mode, the WYSIWYG editor will execute the macro and feed the result back into the document. If your macro use some JSX, these will not be loaded. But, if your macro produce some Javascript that use those JSX or manipulate the document's DOM (injecting new elements, moving existing elements, removing elements, etc.), you may want to protect the content in WYSIWYG edit mode in order to prevent the performed transformation to get saved. Here is how you can prevent this behavior:
101
102 {{code language="velocity"}}
103 {{velocity}}
104 #if("$xcontext.action" != "edit")
105 {{html}}
106 <script type="text/javascript">
107 //<![CDATA[
108 ... some javascript ...
109 // ]]>
110 </script>
111 {{/html}}
112 #end
113 ##
114 ## Rest of the code.
115 {{velocity}}
116 {{/code}}
117
118 = Scripting Tips =
119
120 Following are a few useful hints if you plan to do advanced scripting inside your wiki macros:
121
122 * Access parameters: Use the context object (Ex. ##$xcontext.macro.params.param1##)
123 * Access macro body (if your macro defines one): Use the context object (Ex. ##$xcontext.macro.content##)
124 * Access [[MacroTransformationContext>>http://svn.xwiki.org/svnroot/xwiki/platform/core/trunk/xwiki-rendering/xwiki-rendering-api/src/main/java/org/xwiki/rendering/transformation/MacroTransformationContext.java]]: Use the context object (Ex. ##$xcontext.macro.context##)
125 * Since 2.4M1, it's possible to directly return the desired list of rendering blocks without having to render them first to let them be parsed back by the macro transformation. The benefits are that it could be a lots quicker and most of all it means supporting syntax which does not provide any renderer. It also makes it possible to generate some XDOM which is impossible to write in any some syntax. For example the following wiki macro is generating a LinkBlock targeting a relative URL:(((
126 {{code language="groovy"}}
127 {{groovy}}
128 import java.util.Collections;
129 import org.xwiki.rendering.listener.Link;
130 import org.xwiki.rendering.block.WordBlock;
131 import org.xwiki.rendering.block.LinkBlock;
132
133 ref link = new Link();
134 link.setReference("/xwiki/edit/Main/WebHome");
135 link.setType(LinkType.URI);
136
137 ref linkBlock = new LinkBlock(Collections.singletonList(new WordBlock("Edit home page"))), link, false);
138
139 xcontext.macro.result = Collections.singletonList(linkBlock)
140 {{/groovy}}
141
142 This text will not appear in the result.
143 {{/code}}
144 )))
145 * If you are using ##$xcontext.macro.content## in your velocity macro, that content will not be able to support scripting, since nested scripting is not supported. To workaround that limitation, thanks to the above, you may do the parsing yourself using the rendering service. Here is a small sample:(((
146 {{code languege="velocity"}}
147 {{velocity output="no"}}
148 ## get the macro content in a velocity string
149 #set($wikiresult = $xcontext.macro.content)
150 ## Add a wrapping div as a sample of the action of this macro
151 #set($wikiresult = "(% class='newstyle' %)((($wikiresult)))")
152 ## parse the string and return the resulting blocks
153 #set($xcontext.macro.result = $services.rendering.parse($wikiresult, $xwiki.getCurrentContentSyntaxId()).getChildren())
154 {{/velocity}}
155 {{/code}}
156 )))
157
158 = Troubleshooting =
159
160 == A Pitfall of Optional Parameters ==
161
162 {{info}}
163 This pitfall has been fixed in XWiki 2.2
164 {{/info}}
165
166 There is a common pitfall for using optional paramters. The following macro code contains a not so obvious bug:
167
168 {{code languege="velocity"}}
169 {{velocity}}
170 #set($greetUser=$xcontext.macro.params.greetUser)
171 #if ("true" == $greetUser && "XWiki.XWikiGuest" != "$xcontext.user" )
172 Hello $xwiki.user.email!
173 #else
174 Hello world!
175 #end
176 <img src="$image" width="$width" />
177 {{/code}}
178
179 If we invoke it twice in a row:
180
181 {{code}}
182 {{hello greetUser="true" /}}
183 {{hello /}}
184 {{/code}}
185
186 The second invocation will not print "Hello World!" as we'd expect. But it will print the same result as the first invocation. The reasons are:
187
188 * Macro parameters are implemented as global parameters. So, they remain the same across multiple macro invocations.
189 * If ##$xcontext.macro.params.greetUser## contains "null", it will not be assigned to ##$greetUser##. This is different from C/C++ or Java.
190
191 So in order to get around it, you can use:
192
193 {{code}}
194 #set($greetUser="$!xcontext.macro.params.greetUser")
195 {{/code}}

Get Connected