TheShun
TheShun

Reputation: 1218

Encode and pass HTML from PHP to Javascript

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>

Upvotes: 1

Views: 1972

Answers (1)

bassxzero
bassxzero

Reputation: 5041

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;

Upvotes: 1

Related Questions