Inserting a javascript snippet into a layout template

Topics: General
Nov 18, 2010 at 10:27 AM

Hi,

I'm trying to insert a javascript snippet into a layout template. I have problem with character '>' which always will convert to '>' and this causes the script to fail.

Is there any solution to have a piece of javascript code untouched.

Nov 18, 2010 at 10:34 AM

I tried to use  <![CDATA[...script...]]> but then another a syntax error was raised because of  <![CDATA[\n

Coordinator
Nov 18, 2010 at 10:57 AM

Hi

Try to check this simple example, on the layout template put this code within <head> section:

<head>
       
<script type="text/javascript">
//<![CDATA[
alert("Hello World!");
//]]>
</script>
</head>

Nov 18, 2010 at 11:16 AM

Thanks @Inna.

Adding // did the job.

Dec 2, 2010 at 3:58 AM
Edited Dec 2, 2010 at 3:59 AM

I am again seeing this issue. 

I have moved the script to another XSL function and then call that function in <header> tag in a template.

My only issue is that composite converts '>' to &gt; which makes the javascript code fail. For example here is my code below:

<script type="text/javascript">      

// <![CDATA[

$(document).ready(function() {

if (1 > 0) {

alert('hello');

 }); } });

//]]>

</script>

The all I get in FireBug console is :

 

missing ) after condition

 

I thought we have solved this issue. Maybe after I upgraded to SP1 this is showing again. not sure.
Any idea?

 

Coordinator
Dec 2, 2010 at 8:02 AM
Edited Dec 2, 2010 at 8:49 AM

Hi Aboo

 

My guess is - when you use a "<![CDATA[ .... ]]> " in XSLT, it inserts its content (XML encoded) rather than a CDATA section.

In order not to have the script encoded you can try to render the following xhtml:

 

<script type="text/javascript">  
// <!--
$(document).ready(function() {

if (1 > 0) {
   alert('hello');
 }); } });
// -->
</script>

 

the xslt code to produce such markup will look like:

 

<script type="text/javascript">      

// <xsl:comment> <![CDATA[

$(document).ready(function() {
  if (1 > 0) {
     alert('hello');
  }); } });

// ]]></xsl:comment>

</script>

 

Dec 2, 2010 at 8:31 AM

That solved the issue. Thanks.

Jun 22, 2012 at 7:52 PM
Edited Jun 22, 2012 at 7:53 PM

I'm only replying to this because I always forget the syntax of this and how best to incorporate javascript into an XSLT template and I hate searching for it all the time. 

And also want to point out that it's important that <xsl:comment> <![CDATA[ stays on the same line as the commented out code. The reason that I say this is because Visual Studio likes to reformat things and drops it to another line. For this reason, I recommend using /* */ comments:

<script type="text/javascript">      

/*  <xsl:comment> <![CDATA[ */
$(document).ready(function() {
  if (1 > 0) {
     alert('hello');
  }); } });
/* ]]></xsl:comment> */

</script>