Writing XWiki Rendering Macros in wiki pages

Last modified by Simon Urli on 2023/10/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!

This page is a tutorial but you can also access the reference documentation for the Wiki Macro feature.

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. You will need to be advanced to access the object editor.

There can be only one object of type XWiki.WikiMacroClass per wiki page (if you add more only the first will be used).

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
  • 14.4+ Default categories: Default categories under which this macro should be listed (<14.4 It was called "Default category")
  • Supports inline mode: Whether the macro can be used in an inline context or not
  • Macro content availability: Whether this macro should support a body or not. Valid values are "Optional", "Mandatory" and "No Content".
  • Macro content type: The type of accepted content: two values are proposed, WIKI if this content should be editable like a wiki content, or UNKNOWN if it should be displayed like a plain text. It's also possible to specify a custom java type such as java.util.List<java.lang.String>. Leaving the field blank is equivalent to UNKWOWN value.
  • 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)
  • Priority: The priority of execution relative to the other Macros. The lowest values have the highest priorities and execute first. For example a Macro with a priority of 100 will execute before one with a priority of 500. The default value is 1000.
  • Asynchronous rendering: Enabled or disable asynchronous rendering of the panel. Disabled by default.
  • Cached: Indicate if the result of the execution of the element should be cached. Disabled by default.
  • Context elements: The context information required during the execution of the extension (current user, current document, etc.). It's also used to generate the cache key.

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.1 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

The easiest way to insert the content of the wiki macro is to use a dedicated macro in the body of the wikimacro:

{{wikimacrocontent/}}

Note that by default this makes the content of the macro directly editable in the WYSIWYG editor.

For more details, see the Scripting Tips section below.

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 (optional): 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
  • Parameter default value (optional): The default value of the parameter when it's empty
  • Parameter type (optional): Indicates to which Java type the parameter value (defined as a String). Two values are proposed, WIKI if this parameter contains wiki content, or UNKNOWN if it should be displayed like a plain text. It's also possible to specify a custom java type such as java.util.List<java.lang.String>. Leaving the field blank is equivalent to UNKWOWN value.
    • This is needed when using the {{wikimacroparameter}} macro (see below), which uses this type to decide how to render the macro parameter.
    • For more information about parameter types and parameter pickers, see: Using pickers for XWiki Rendering Macro parameters

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:

{{velocity}}
#if ($wikimacro.parameters.greetUser && "XWiki.XWikiGuest" != "$xcontext.user")
   Hello $services.rendering.escape($xwiki.user.email, 'xwiki/2.1')!
#else
   Hello world!
#end
{{/velocity}}

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 $wikimacro.parameters.greetUser. We plan to introduce some form of direct parameter binding in the future.

It is also possible to display the content of a macro parameter by using a dedicated macro:

Hello {{wikimacroparameter name="greetUsers" /}}

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

{{hello greetUser="true"/}}

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:

{{velocity}}
#set ($greet = true)
{{hello greetUser="$greet"/}}
{{/velocity}}

Translations

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) 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):

rendering.macro.<macro id>.name=Name of the macro, displayed in the macros list in the macros wizard
rendering.macro.<macro id>.description=Description of the macro, displayed as a help in the macros list in the macros wizard

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
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

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.

In our example, french translations would be something like this:

rendering.macro.hello.name=Macro pour dire bonjour
rendering.macro.hello.description=Ceci est une macro qui va dire "Bonjour" a l'utilisateur
rendering.macro.hello.parameter.greetUser.name=Personnaliser le message
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).

Macro Visibility and Rights

There are 3 levels of visibility for a macro:

  • Global
    • on the main wiki, the macro will be available in all the pages of all the (sub)wikis. Requires the macro author to have Programming Rights
    • on subwikis, it's a synonym of the Current Wiki visibility
  • 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
  • Current User, which means that the macro will only be available to the user who is its author. No special rights required.

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.

Bindings

The usual XWiki scripting context bindings are available in the scripts of the wiki macros, with the mention that contextual variables (such as $doc) will point to the XWiki document (page) in which the macro is called, not to the XWiki document containing the objects that define the macro. This makes it easy to write features that are contextualized to the page where they're called.

Then, specific bindings for the wiki macro context are available, see the reference documentation page.

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

macro4.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}}

WYSIWYG editing of macro content or parameter

As specified above you can use the dedicated macros {{wikimacrocontent/}} and {{wikimacroparameter name="foo"/}} to allow the users of your macro to be able to edit the values of the macro directly in the WYSIWYG editor once the macro is inserted.
Note that this is currently only possible if you specified that the macro content (or parameter) type is WIKI type.

There is also a known limitation related to CKEditor that prevents editing directly those macros if they are not used as "standalone" macro. Details can be found on the related issue.

Scripting Tips

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

  • 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);

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

    This text will not appear in the result.
  • If you need to directly access the parsed XDOM of the content 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 = $wikimacro.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($wikimacro.result = $services.rendering.parse($wikiresult, $xwiki.getCurrentContentSyntaxId()).getChildren())
    {{/velocity}}
Tags:
   

Get Connected