Question How Do I Embed Xwiki Code As Text?

Including XWiki code as part of your text. (Escaping Xwiki code)

Sometimes, especially when we are trying to create these FAQs and documentation for Xwiki, we will need to display XWiki programming code as part of our text. For example, if we are trying to write a tutorial on how to create a Blog in XWiki.

If you simply put the code inside the standard {code} tags, the rendering engine will still execute it. The reason is that the special characters "#" and "$" must be escaped. When the rendering engine sees that this character is escaped, it ignores it as a processing instruction and then just displays it.

The escape character for Xwiki code is the backslash "
" character.

So, to include a code section, type it in like this:

\\#set(\$page = \$doc.fullName)

If you type the previous code into your document exactly as it appears, with the backslashes, the resulting output would look like:

\#set(\$page = \$doc.fullName)

If it is a large piece of code, type or paste it into a seperate document that people wont see directly. In this example we will use a document that contains the Blog code most people use: BlogMacro

Dev.BlogMacro contains no textual content, it is just the code for the Blog list. To get it into this document, use the following code:

\#set(\$code = \$xwiki.getDocument("Doc.BlogMacro").content)
\#set(\$code = \$code.replace("\#","\\\#"))
\#set(\$code = \$code.replace("\$","\\\$"))

An example of the output of the preceding code is:

#set($code = $xwiki.getDocument("Doc.BlogMacro").content)
#set($code = $code.replace("#","\\#"))
#set($code = $code.replace("$","\\$"))

And thats how you would embed code. It was wierd embeddeding code to show how to embed code, so if you wanna see my headache, view the code for this page. You'll LOVE it!

In the meantime, if you want to know how I escaped the esacape character. Well, you can display a single backslash character by typing in three backshashes in a row, like: "

However, if I had actually tried to show three escaped backslashes in a row, it would have been a mess, if not impossible, therefore, I simply used the backslash HTML Identity Reference, which is 92. Pretty slick huh? :-p


Get Connected