Macro with velocity: use current document

Hi.

I’m trying to write a small macro listing all attachments of the document where the macro is inserted. My code so far:

{{velocity}}
  ##$doc
  #foreach($attachment in $doc.getAttachmentList())
    * [[$attachment.getFilename()>>attach:$attachment.getFilename()]]
  #end
{{/velocity}}

Funny thing is: As long as I am editing and just inserting this macro with the WYSIWYG editor I can see all attachments of the article I am editing. But after saving and viewing the list is empty.

For debugging I inserted that line

$doc

This is switching from the current article to Main.WebHome when I saved + viewed it.

Why is this happening and how to avoid this?
Regards, Simpel

Just tried your code and it’s working fine, $doc is the doc where the macro is used.

My guess is that you’re using it inside a panel

If your macro is used in an async context, you need to make sure that the doc reference is passed to it I think, see https://extensions.xwiki.org/xwiki/bin/view/Extension/Rendering%20Module/Async/ (panels are executed async for information).

Now TBH, I also can’t make it work inside a panel (even when selecting all the “Context elements”). cc @tmortagne

1 Like

That’s the solution for my issue. I did select “async rendering yes” without really needing it. Switching to “no” solved my problem.

Thank you.

Ok I’ve solved it on my side too. The panel can be async but you need to select “Document” in its context items (I was wrongly selecting “Document” in the macro context elements but my macro wasn’t async and the panel was async without the right context elements).