guigrpa / docx-templates

Template-based docx report creation
MIT License
904 stars 146 forks source link

insert references #257

Closed DeveloperOl closed 2 years ago

DeveloperOl commented 2 years ago

Hi @all, thanks for this awesome software. I was wondering if it is possible to create a dynamic reference inside the document with a custom text. For example a reference to a headline, which directs to the underlying headline when clicked. Is it possible to this in the current state?

jjhbw commented 2 years ago

I'm not really a Word power user so i'm not sure exactly which functionality you mean.

You can try by wrapping the reference you want in an IF statement to conditionally render it.

DeveloperOl commented 2 years ago

@jjhbw Sorry maybe that was not clearly stated. I mean the cross-reference function in word. A cross reference is like a link in the same document, e.g. to a headline. So in a text blob I can have a link "click ->here<-" and when clicked it directs to a chapter in the same document, not an external address.

jjhbw commented 2 years ago

There is no convenience command to inject such a link.

You can take a look at injecting raw, dynamically generated (i.e. in JS) XML literals into your template. See README on how to do that. You'd have to find out yourself how the XML for the links you want looks, though.

Alternatively, you can try something like the below in your template.

+++IF condition_a+++
<another link in Word to e.g. headline 2>
+++END-IF+++

+++IF condition_b+++
<another link in Word to e.g. headline 5>
+++END-IF+++

Does that answer your question?

DeveloperOl commented 2 years ago

@jjhbw I will have a look into the XML documentation. Is there a good reference/documentation for the literal XML? The readme is really quite on that topic

jjhbw commented 2 years ago

Yes the README doesn't cover it because it is out of scope of this library. The docx spec is simply too large to make abstractions for everything, see http://officeopenxml.com/anatomyofOOXML.php

jjhbw commented 2 years ago

Hope this helped. If not, feel free to reopen.

DeveloperOl commented 2 years ago

Sorry for my late reply. Let me share my solution for others having the same issue:

I used literal XML to by creating headline objects consisting of a unique ID and a headline text. using literal XML I created a headline text with a bookmark of the headline object, like:

||<w:bookmarkStart w:id="${headline.uid}" w:name="${headline.uid}"/><w:r><w:t>${headline.text}</w:t></w:r><w:bookmarkEnd w:id="${headline.uid}"/>||

Now I used hyperlinks to reference to the bookmark anywhere in the document, like:

||<w:hyperlink w:anchor="${headline.uid}"><w:r><w:t>THIS IS A LINK</w:t></w:r></w:hyperlink>||

Thank you @jjhbw, the documentation helped a lot :)

jjhbw commented 2 years ago

Thanks for posting your solution, much appreciated!