Version 96.3 by Adel Atallah on 2018/11/16

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 This page is a tutorial but you can also access the [[reference documentation for the Wiki Macro feature>>doc:extensions:Extension.WikiMacroStore.WebHome]].
8
9 = Macro Visibility and Rights =
10
11 There are 3 levels of visibility for a macro:
12
13 * ##Global##
14 ** on main wiki (or {{info}}before XWiki 10.4RC1{{/info}}) the macro will be available in all the pages of all the (sub)wikis. Requires the macro author to have **Programming Rights**
15 ** on subwiki {{info}}in 10.4RC1+{{/info}} synonym of ##Current Wiki## visibility
16 * ##Current Wiki##, which means that the macro will be available in all the pages of the wiki the macro is in. Requires the macro author to have **Admin Rights**
17 * ##Current User##, which means that the macro will only be available to the user who is its author. No special rights required.
18
19 == Using protected API in wiki macros ==
20
21 Also, if the macro needs to use [[protected API>>platform:DevGuide.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.
22
23 = Hello Macro =
24
25 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.
26
27 == Definition ==
28
29 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##.
30
31 {{warning}}
32 There can be only one object of type ##XWiki.WikiMacroClass## per wiki page (if you add more only the first will be used).
33 {{/warning}}
34
35
36 This class contains the following fields:
37
38 * Macro id: Id of the macro to be used by users when invoking your macro from wiki code
39 * Macro name: Name of the macro to be displayed on the wysiwyg editor
40 * Macro description: A short description of the macro to be displayed on the WYSIWYG editor
41 * Default category: Default category under which this macro should be listed
42 * Supports inline mode: Whether the macro can be used in an inline context or not
43 * Macro content type: Whether this macro should support a body or not
44 * Content description: A short description about the macro's content to be displayed on the WYSIWYG editor
45 * 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)
46
47 Now we can define our hello macro as shown below:
48
49 [[image:macro1.png]]
50
51 == Invocation ==
52
53 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:
54
55 {{code}}
56 {{hello/}}
57 {{/code}}
58
59 And if you view the result it would say "Hello World!" (of course).
60
61 == Content ==
62
63 If macro content is used, it can be shown by executing the following velocity code in the macro body:
64
65 {{code language="none"}}
66 {{velocity}}$xcontext.macro.content{{/velocity}}
67 {{/code}}
68
69 For more details, see the [[Scripting Tips section below>>platform:DevGuide.WikiMacroTutorial||anchor="HScriptingTips"]].
70
71 == Parameters ==
72
73 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:
74
75 * Parameter name: Name of the parameter, users will refer this name when invoking your macro with parameters
76 * Parameter description: A short description of the parameter, this description will be made available on the WYSIWYG editor
77 * Parameter mandatory: Indicates if this particular parameter is mandatory, wiki macro will fail to execute if a mandatory parameter is missing
78 * Parameter default value: The default value of the parameter when it's empty
79 * Parameter type: Indicates in which type the parameter value should be converted in (java.lang.String by default)
80
81 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:
82
83 [[image:macro3.png]]
84
85 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:
86
87 [[image:macro4.png]]
88
89 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.
90
91 Finally, we can test our new version of **hello macro** with the following invocation:
92
93 {{code language="none"}}
94 {{hello greetUser="true"/}}
95 {{/code}}
96
97 If you want to call the new version of the **hello macro** with a parameter from a variable you will need to wrap the call in a velocity macro like this:
98
99 {{code language="none"}}
100 {{velocity}}
101 #set ($greet = true)
102 {{hello greetUser="$greet"/}}
103 {{/velocity}}
104 {{/code}}
105
106 == Translations ==
107
108
109
110 When your macro is ready, you might want to provide the description of the macro and its parameters in different languages. For that, you need to create a set of translation keys and values (as described [[here>>platform:DevGuide.InternationalizingApplications]]) and then just use the following convention for the keys you add in this storage (no modification is needed on the macro itself, the association of the translations to the macro is done based on a convention of the form of the translation keys):
111
112 {{code}}
113 rendering.macro.<macro id>.name=Name of the macro, displayed in the macros list in the macros wizard
114 rendering.macro.<macro id>.description=Description of the macro, displayed as a help in the macros list in the macros wizard
115
116 rendering.macro.<macro id>.parameter.<parameter name>.name=Name of the macro parameter, to be displayed in the form for the macro settings in the macros wizard
117 rendering.macro.<macro id>.parameter.<parameter name>.description=Description of the macro parameter, to be displayed as a help in the form for the macro settings in the macros wizard
118 {{/code}}
119
120 Don't forget to make sure that the visibility of the translations is the same as the visibility of the macro, so that anywhere you use the macro you also have the translations.
121
122 In our example, french translations would be something like this:
123
124 {{code}}
125 rendering.macro.hello.name=Macro pour dire bonjour
126 rendering.macro.hello.description=Ceci est une macro qui va dire "Bonjour" a l'utilisateur
127 rendering.macro.hello.parameter.greetUser.name=Personnaliser le message
128 rendering.macro.hello.parameter.greetUser.description=Personnaliser le message pour l'utilisateur courant en train de visualiser la page. Les valeurs possibles sont "true" (oui) et "false" (non).
129 {{/code}}
130
131 = WYSIWYG Access =
132
133 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:
134
135 [[image:macro2.png]]
136
137 [[image:macro5.png]]
138
139 == Special code for WYSIWYG edit mode ==
140
141 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:
142
143 {{code language="velocity"}}
144 {{velocity}}
145 #if("$xcontext.action" != "edit")
146 {{html}}
147 <script type="text/javascript">
148 //<![CDATA[
149 ... some javascript ...
150 // ]]>
151 </script>
152 {{/html}}
153 #end
154 ##
155 ## Rest of the code.
156 {{/velocity}}
157 {{/code}}
158
159 = Scripting Tips =
160
161 Following are a few useful hints if you plan to do advanced scripting inside your wiki macros:
162
163 * Access parameters: Use the context object (Ex. ##$xcontext.macro.params.param1##)
164 * Access macro body (if your macro defines one): Use the context object (Ex. ##$xcontext.macro.content##)
165 * Access [[MacroTransformationContext>>https://github.com/xwiki/xwiki-rendering/blob/master/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/main/java/org/xwiki/rendering/transformation/MacroTransformationContext.java]]: Use the context object (Ex. ##$xcontext.macro.context##)
166 * 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:(((
167 {{code language="groovy"}}
168 {{groovy}}
169 import java.util.Collections;
170 import org.xwiki.rendering.listener.Link;
171 import org.xwiki.rendering.block.WordBlock;
172 import org.xwiki.rendering.block.LinkBlock;
173
174 ref link = new Link();
175 link.setReference("/xwiki/edit/Main/WebHome");
176 link.setType(LinkType.URI);
177
178 ref linkBlock = new LinkBlock(Collections.singletonList(new WordBlock("Edit home page"))), link, false);
179
180 xcontext.macro.result = Collections.singletonList(linkBlock)
181 {{/groovy}}
182
183 This text will not appear in the result.
184 {{/code}}
185 )))
186 * 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:(((
187 {{code languege="velocity"}}
188 {{velocity output="no"}}
189 ## get the macro content in a velocity string
190 #set($wikiresult = $xcontext.macro.content)
191 ## Add a wrapping div as a sample of the action of this macro
192 #set($wikiresult = "(% class='newstyle' %)((($wikiresult)))")
193 ## parse the string and return the resulting blocks
194 #set($xcontext.macro.result = $services.rendering.parse($wikiresult, $xwiki.getCurrentContentSyntaxId()).getChildren())
195 {{/velocity}}
196 {{/code}}
197 )))
198 * Since 9.1RC1 you can access the macro descriptor using ##$xcontext.macro.descriptor## binding. It returns a ##org.xwiki.rendering.macro.descriptor.MacroDescriptor## Java object.
199
200 = Troubleshooting =
201
202 == A Pitfall of Optional Parameters ==
203
204 {{info}}
205 This pitfall has been fixed in XWiki 2.2
206 {{/info}}
207
208 There is a common pitfall for using optional paramters. The following macro code contains a not so obvious bug:
209
210 {{code languege="velocity"}}
211 {{velocity}}
212 #set($greetUser=$xcontext.macro.params.greetUser)
213 #if ("true" == $greetUser && "XWiki.XWikiGuest" != "$xcontext.user" )
214 Hello $xwiki.user.email!
215 #else
216 Hello world!
217 #end
218 <img src="$image" width="$width" />
219 {{/code}}
220
221 If we invoke it twice in a row:
222
223 {{code}}
224 {{hello greetUser="true" /}}
225 {{hello /}}
226 {{/code}}
227
228 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:
229
230 * Macro parameters are implemented as global parameters. So, they remain the same across multiple macro invocations.
231 * If ##$xcontext.macro.params.greetUser## contains "null", it will not be assigned to ##$greetUser##. This is different from C/C++ or Java.
232
233 So in order to get around it, you can use:
234
235 {{code}}
236 #set($greetUser="$!xcontext.macro.params.greetUser")
237 {{/code}}

Get Connected