Today I had to create HTML element identifiers with one of our macros for Confluence. I realized that our way of generating HTML 4 IDs had not been compatible with the solution Confluence offered. So I tried to find the service class that runs the HTML element ID generation.
It turned out that it is easily accessible via the conversation context. :-)
HTML 5 vs HTML 4
First I had been confused since the IDs generated by Confluence for their headings contained non-ASCII characters. But Confluence creates HTML 5 content and therefore identifiers simply must not be empty and not contain spaces.
Quote External | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters. |
...
So I removed our HTML 4 compatible ID generation code.
Confluence's HTML ID Creator
I looked for the service class and finally found a little helper class in com.atlassian.confluence.content.render.xhtml.HtmlElementIdCreator
, which is an implementation of com.atlassian.confluence.content.render.xhtml.ElementIdCreator
.
This implementation makes it easy to actually create unique identifiers. If a non-unique title is encountered, the helper adds a dot with a running number (e.g. MyPage-MyTitle.1
for the second title), ensuring its uniqueness.
...
Note Box | |
---|---|
Note the basic pattern:
|
...
|
...
But, as a Confluence user, you will normally not get in touch with this details. If you edit a link via the visual editor, you simply specify page title and heading on the Advanced tab. |
...
It is very easy to access an instance of ElementIdCreator
from the conversion context.
Code Block | ||
---|---|---|
|
...
final PageContext pageContext = conversionContext.getPageContext(); |
...
final ElementIdCreator creator = pageContext.getElementIdCreator(); |
...
Note that the documentation to getPageContext()
says that it is almost deprecated, but I found no other way to access the creator instance.
Conversion is straight forward, with basis
being a reference to a character sequence you want to transform to an HTML 5 identifier:
...
Code Block | ||
---|---|---|
| ||
final String html5Id = creator.generateId(basis); |
...
If you are not interested in ensuring uniqueness of your ID, you may use the static method of HtmlElementIdCreator
:
Code Block | ||
---|---|---|
|
...
final String html5Id = HtmlElementIdCreator.convertToIdHtml5(alreadyUniqueId); |
...
Conclusion
Using the implementation of the ElementIdCreator
interface helps to integrate your macro generating identifiers smoothly into Confluence.
The Section
...
Macro from our projectdoc for Confluence
...
add-on use this facility since version 1.1.0 (PDAC-242).
Please visit projectdoc for Confluence for more information on projectdoc or watch our new video introduction to projectdoc.