Brief Backstory
I am not going to bore anyone with a bunch of chatter and mindless ramblings for this one. The reason for this situation is quite simple: Blogger uses an XML parser to create the HTML seen on a page. Templates in Blogger are just XML templates and XML has a few reserved characters that have special meaning (see references below) and if you haven't worked with XML, using those characters results in a XML parsing error because the parser doesn't know what to do with them.Fortunately, the XML standard defines a way to specify character data in XML documents that could contain special characters, or other data, that should not be parsed as XML. These sections are known as "CDATA Sections" and are denoted with a starting tag of "<![CDATA[" and an ending tag of "]]>". Wrapping any content with these tags will cause the XML parser to ignore them as XML data.
The Solution
Referring to my Working with Syntax Highlighter in Blogger Simplified post, a condition that would look like this in the template markup of Blogger:
[pre class="brush:jscript;" title="Script with character entities"]
<script type="text/javascript">
// a bunch of previous code
if ((n1 != null &amp;&amp; n2 != null) &amp;&amp; (n1.tagName == n2.tagName)) {
n2.parentNode.removeChild(n2);
}
// a little more code
</script>
[/pre]
Becomes what you expect Javascript to look like:
[pre class="brush:jscript;" title="Clean JS in Blogger"]
<script type="text/javascript">
//<![CDATA[
// a bunch of previous code
if ((n1 != null && n2 != null) && (n1.tagName == n2.tagName)) {
n2.parentNode.removeChild(n2);
}
// a little more code
//]]>
</script>
[/pre]
Just go ahead and wrap any Javascript you add to your templates with those CDATA tags and you shouldn't run into any XML parsing errors with your script. And you don't have to go looking for those entity references when it's late at night and you can't think straight.
The sad thing for me is that it took a little while for the solution to click. I have had to use this approach many times in the past with some of the CMS' I have worked with, since many CMS' either still utilize, or at least began life by utilizing XML. I don't know why it didn't dawn on me when I was trying to get my script into my Blogger template in the first place.
References:
Working with Syntax Highlighter in Blogger SimplifiedCharacter and Entity References - MSDN reference
Which are the HTML, and XML, special characters? - Stack Overflow question
XML Predefined Entities - W3 XML Spec
CDATA Sections - W3 XML Spec
This comment has been removed by a blog administrator.
ReplyDeletenice
ReplyDeleteNice Post
ReplyDelete