What is a proper way to include stylesheets when macro is included in a page?

Let’s say I have a page for macro: Navigation Box and I add object of type XWiki.WikiMacroClass to it. And I add this text to the macros:

{{velocity}}
{{html wiki="true" clean=false}}
<ul class="NavBox">
<li>[[Item1]]</li>
<li>[[Item2]]</li>
<li>[[Item3]]</li>
</ul>
{{/html}}
{{/velocity}}

Then in any page I can include this macro with {{NavBox}}. And now I want to add custom styles for it. I just do display:none for testing. When I googled it, I found in the documentation that I can either add skin extension or embed it in the {{html}} macro. When I add object of type XWiki.StyleSheetExtension to the page on which the macro is on and then include the macro, the styles don’t get added. Which kinda makes sense. So I add the styles to the {{html}} macro:

<style>
.NavBox {
  display: none;
}
</style>

This works but it feels like a hack. It’s no different than embedding the styles in your html normally. Feels like the preferred way for this case would be to add the styles to the XWiki.StyleSheetExtension object, but then I’d have to include that object in the page separately from the macro, which also feels like a hack.

I also tried to add the macro to the page to which it is attached and then include the whole page in some other page using the {{include}} macro, but even then it doesn’t add the styles to the page in which it is included.

I can include the StyleSheetExtension on the whole wiki, but that feels suboptimal, too.

Should I just do one of the options that I know works or should I do something else, better than this?

Managed to find what I think is a good solution here, I include the stylesheet manually in the macro:

{{velocity}}
#set ($discard = $xwiki.ssx.use("Main.Navigation Box.WebHome"))
{{html wiki="true" clean=false}}
<ul class="NavBox">
<li>[[Item1]]</li>
<li>[[Item2]]</li>
<li>[[Item3]]</li>
</ul>
{{/html}}
{{/velocity}}

But what will happen if I move the page itself? For example, if I rename the pave from Navigation Box to NavBox? Looks like it will stop working? I feel like it will be more correct if I do something like this:

{{velocity}}
#set ($pageToWhichMacroIsAttached = somehowGetPageToWhichThisMacroIsAttached()
#set ($discard = $xwiki.ssx.use($pageToWhichMacroIsAttached))
{{/velocity}}

But how do I get the page to which this macro is attached? $doc won’t work here since it’ll return where this macro is being rendered, from what I understand so far.

Managed to fix my problem. The variable I was looking for is $wikimacro.doc. Now everything works even if page is moved:

{{velocity}}
$xwiki.ssx.use($wikimacro.doc)
{{html wiki="true" clean=false}}
<ul class="NavBox">
<li>[[Item1]]</li>
<li>[[Item2]]</li>
<li>[[Item3]]</li>
</ul>
{{/html}}
{{/velocity}}

844711388134768661

2 Likes