HowDoIEmbedXwikiCodeAsText

Last modified by Vincent Massol on 2007/06/14

Question How Do I Embed Xwiki Code As Text?
Answer

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:

\{code\}
\\#set(\$page = \$doc.fullName)
\\#includeForm("Test.BlogMacro") 
\{code\}

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)
\#includeForm("Test.BlogMacro")

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: Blog Macro?

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:

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

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("$","\\$"))
$code
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

Tags:
Created by AndyCarrasco on 2005/11/02
   

Get Connected