Invenzzia »

JavaScript code escaping

From Invenzzia wiki

Jump to: navigation, search

The OPT XML parser recognizes and parses the CDATA sections, but in this particular case the default XML semantics is not useful for us - the following code will surely escape the Javascript, but also will produce an unparseable output:

The template:

<script type="text/javascript">
<![CDATA[
document.write('Hello my friend, do you need {$object} or ]]>{$object}<![CDATA[?');
]]>
</script>

Output:

<script type="text/javascript">
<![CDATA[
document.write('Hello my friend, do you need {$object} or ]]>sunglasses<![CDATA[?');
]]>
</script>

Fortunately, OPT contains the opt:literal that allows the intelligent CDATA parsing:

The template:

<script type="text/javascript">
<opt:literal type="comment_cdata">
<![CDATA[
document.write('Hello my friend, do you need {$object} or ]]>{$object}<![CDATA[?');
]]>
</opt:literal>
</script>

Output:

<script type="text/javascript">
/* <![CDATA[ */
document.write('Hello my friend, do you need {$object} or sunglasses?');
/* ]]> */
</script>

Note that opt:literal can generate also other types of delimiters.

It is important to use comment_cdata value of type attribute of opt:literal instruction with JavaScript and CSS code in order to have it work correctly on all browsers. Pure CDATA block causes problems on older browsers and single comment is not parsed in correct xhtml document.

Personal tools