1

i need to pass an html template to a javascript variable in php

i tried differents things like json_encode(), str_replace() addcslashes() but javascript always throw an error of unexpected character

<?php
$html = file_get_contents('template.html');

function escapeJavaScriptText($string)
{
    return str_replace("\n", '\n', str_replace('"', '\"',      addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
?>

<script> var template = "<?php echo escapeJavaScriptText($html)  ?>"</script>
3
  • You can try str_replace (array("\r\n", "\n", "\r"), ' ', $html). But are you sure it's best solution? to pass an html template to a javascript variable in PHP ;)? Commented Nov 22, 2016 at 13:18
  • i'm not sure :D but i need my html template and my js in the same js file Commented Nov 22, 2016 at 13:24
  • yes, sorry this is just an error in the example Commented Nov 22, 2016 at 13:49

1 Answer 1

1

I always use a <script> tag to hold my HTML templates. It's a habit I learned from using Handlebars JS. http://handlebarsjs.com/

The trick is the type="text/html" attribute, the browser doesn't know what do with it so it doesn't display it and doesn't try to run it as code.

<script type="text/html" id="Template1">
    <p>This is a template</p>
    <p>More template stuff</p>
</script>

To access the template you can do something like

JQuery:

$('#Template1').html()

Javascript:

document.getElementById('Template1').innerHTML;
Sign up to request clarification or add additional context in comments.

3 Comments

looks good, is it ok to put multiple <script> tags in the same .js file ?
@TheShun I don't see why you couldn't, but I've only ever done it with one.
i just tried, i can't use this method since my script is a .js file already embeded in a script src tag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.