views:

120

answers:

3

Suppose I am using an MVC framework, and my views require Javascript files located in a file external to the view. My javascript located in the external file depends, however, upon a few PHP variables in my view. If I were to include the Javascript in a tag inside my HTML view, I could simply inject the PHP variables into the Javascript.

I know I can create hidden input fields and assign the variables I need as their values. Is there another, more elegant way?

I know I could probably get away with naming the .js file to .php, but I'm not too fond of doing that.

+1  A: 

You could make a call from JS to the server (e.g. REST) to get the variables you depend on. You would have to create a service for this but the structure would remain clean.

Gergely Orosz
+4  A: 

I'm not sure I understand your question completely, but if I have the gist right, couldn't you just set global javascript variables inside a script tag in the view, that would then be passed to your external js?

<script type="text/javascript">
  var myvar1 = <?=$myvar1 ?>;
  var myvar2 = "<?=$myvar2 ?>";
</script>
<script type="text/javascript" src="myexternaljs.js"></script>
Travis
+1  A: 

You can either post them on the page before you include other scripts, or use something like this and include the php file like a js file:

ob_start();
//all variables here
echo 'var someJson = '
    . json_enode($someArray);
$content = ob_get_clean();

header('Content-Type: text/javascript');
header('Content-Length: ' . strlen($content)); //or mb_strlen with utf8
echo $content;
exit;

You can add headers to provide caching with etag (hashing/id), last modified or expire/pragma.

OIS