Writing XWiki Rendering Macros in wiki pages

Version 87.1 by Valdis Vitolins on 2013/09/10

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!

Macro Visibility and Rights

There are 3 levels of visibility for a macro:

  • farm (if we're in a multiwiki environment), meaning that the macro will be available in all the wikis of the farm
  • wiki, which means that the macro will be available in its wiki
  • user, which means that the macro will only be available to the user which is its author

The rights required to create macros are different depending on the visibility we want for our macro:

  • the macro author needs to have programming rights for a macro available in the whole farm
  • the macro author needs to have admin rights for a macro available in its wiki
  • no special rights besides the obvious right to edit the page are needed for a macro available only to its author.

Using protected API in wiki macros

Also, if the macro needs to use protected API, 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.

Hello Macro

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.

Definition

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:

  • Macro id: Id of the macro to be used by users when invoking your macro from wiki code
  • Macro name: Name of the macro to be displayed on the wysiwyg editor
  • Macro description: A short description of the macro to be displayed on the WYSIWYG editor
  • Default category: Default category under which this macro should be listed
  • Supports inline mode: Whether the macro can be used in an inline context or not
  • Macro content type: Whether this macro should support a body or not
  • Content description: A short description about the macro's content to be displayed on the WYSIWYG editor
  • 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)

Now we can define our hello macro as shown below:

macro1.png

Invocation

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:

{{hello/}}

And if you view the result it would say "Hello World!" (of course).

Content

If macro content is used, it can be shown by executing following velocity code in macro body:

{{velocity}}$xcontext.macro.content{{/velocity}}

Parameters

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:

  • Parameter name: Name of the parameter, users will refer this name when invoking your macro with parameters
  • Parameter description: A short description of the parameter, this description will be made available on the WYSIWYG editor
  • Parameter mandatory: Indicates if this particular parameter is mandatory, wiki macro will fail to execute if a mandatory parameter is missing

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:

macro3.png

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:

macro4.png

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.

Finally, we can test our new version of hello macro with the following invocation:

{{hello greetUser="true"/}}

WYSIWYG Access

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:

macro2.png 

macro5.png

Special code for WYSIWYG edit mode

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:

{{velocity}}
#if("$xcontext.action" != "edit")
{{html}}
  <script type="text/javascript">
//<![CDATA[
... some javascript ...
// ]]>
</script>
{{/html}}
#end
##
## Rest of the code.
{{velocity}}

Scripting Tips

Following are a few useful hints if you plan to do advanced scripting inside your wiki macros:

  • Access parameters: Use the context object (Ex. $xcontext.macro.params.param1)
  • Access macro body (if your macro defines one): Use the context object (Ex. $xcontext.macro.content)
  • Access MacroTransformationContext: Use the context object (Ex. $xcontext.macro.context)
  • 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:
    {{groovy}}
    import java.util.Collections;
    import org.xwiki.rendering.listener.Link;
    import org.xwiki.rendering.block.WordBlock;
    import org.xwiki.rendering.block.LinkBlock;

    ref link = new Link();
    link.setReference("/xwiki/edit/Main/WebHome");
    link.setType(LinkType.URI);

    ref linkBlock = new LinkBlock(Collections.singletonList(new WordBlock("Edit home page"))), link, false);

    xcontext.macro.result = Collections.singletonList(linkBlock)
    {{/groovy}}

    This text will not appear in the result.
  • 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:
    {{velocity output="no"}}
    ## get the macro content in a velocity string
    #set($wikiresult = $xcontext.macro.content)
    ## Add a wrapping div as a sample of the action of this macro
    #set($wikiresult = "(% class='newstyle' %)((($wikiresult)))")
    ## parse the string and return the resulting blocks
    #set($xcontext.macro.result = $services.rendering.parse($wikiresult, $xwiki.getCurrentContentSyntaxId()).getChildren())
    {{/velocity}}

Troubleshooting

A Pitfall of Optional Parameters

This pitfall has been fixed in XWiki 2.2

There is a common pitfall for using optional paramters. The following macro code contains a not so obvious bug:

{{velocity}}
#set($greetUser=$xcontext.macro.params.greetUser)
#if ("true" == $greetUser && "XWiki.XWikiGuest" != "$xcontext.user" )
 Hello $xwiki.user.email!
#else
 Hello world!
#end
<img src="$image" width="$width" />

If we invoke it twice in a row:

{{hello greetUser="true" /}}
{{hello /}}

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:

  • Macro parameters are implemented as global parameters. So, they remain the same across multiple macro invocations. 
  • If $xcontext.macro.params.greetUser contains "null", it will not be assigned to $greetUser. This is different from C/C++ or Java.

So in order to get around it, you can use:

#set($greetUser="$!xcontext.macro.params.greetUser")
Tags:
   

Get Connected