I have a single page web application using jquery and a set of embedded templates. A template may contain tag like below:
<script type="html/template" id="sample">
<script type="text/javascript" charset="utf-8">alert('x');</script>
</script>
and a jquery code to retrive the template is
$("#sample").html();
The output of above jquery command is
<script type="text/javascript" charset="utf-8">alert('x');
Instead of
<script type="text/javascript" charset="utf-8">alert('x');</script>
How can I fix this output ?
I am not sure this will help you.
var a = $("#sample").html() +'</'+'script>';
alert(a);
fiddle link: http://jsfiddle.net/Sg5W8/
Everything inside a <script>
is expected to be script, not HTML.
The browser sees:
<script type="html/template" id="sample">
and starts interpreting everything that subsequently appears as script, when it reaches the inner <script
its seen as just being text.
The exception to this is </script>
which the browser is looking for in order to switch contexts from script to HTML, so when it sees the 1st </script>
in:
<script type="text/javascript" charset="utf-8">alert('x');</script>
It assumes the opening script block is complete & switches back to expecting HTML, correctly setting the content of the outer script node to:
<script type="text/javascript" charset="utf-8">alert('x');
You can either implement what your trying to do on the server and parsing there, or use a different approach to templating.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With