<?php $str = <<<EOF Test String EOF; ?> <script> var myString = "<?php echo $str ?>"; </script>
If this code is processed by a JS engine e.g in the browser, you will see the following exception:
Fortunately, instead of including complex methods that probably no one will understand, Symfony 1.4 included a lot of helpers like the
UrlHelper and others. Such helpers offer a lot of methods that are frecuently used by developers. One of these helpers is the Escaping helper, that as its name says, include a couple of methods that can be used to escape special characters of strings in different situations. To include this helper on your views/actions you can simply use the
use_helper method and the name of the helper as first argument, that in this case is the Escaping helper:
<?php use_helper("Escaping"); ?>
<?php // Include the Escaping Helper of Symfony 1.4 ?> <?php use_helper("Escaping"); ?> <?php $str = <<<EOF Test String EOF; ?> <script> var myString = "<?php echo esc_js_no_entities($str) ?>"; </script>
PHP will print the following markdown:
<script> var myString = " Test\n String"; </script>
Quick and functional isn't? There are more useful escaping methods in the collection of methods of the Escaping helper like
esc_raw, so don't forget to take a look to the official legacy documentation of the helper here.
Happy coding !