Not for PHP as far as I am concerned. So for PHP and Frontend JavaScript, I guess you could make an AJAX request for loading these data into JSON format.
var request = $.getJSON('/path/to/your/simple/configuration.json');
request.ready(function (configuration) {
// ... your code
});
If you do NodeJS as backend you can share configuration tho, Quoted from here
// common.js
(function(exports) {
// Define all your functions on the exports object
exports.foo = function() {
return 'bar';
};
})((typeof process === 'undefined' || !process.versions)
? window.common = window.common || {}
: exports);
// clientfile.html
<html>
<head>
<script src="common.js"></script>
</head>
<body>
<script>
// window.common.foo()
</script>
</body>
</html>
// nodefile.js
// Using the code from a node.js file
var common = require('./common');
console.log(common.foo());
Thanks for your reply. I would consider an Ajax request a lot more overhead then simply generating global variables in my template. Node.js is not really an option either because I am using Laravel ^^
Another dirty solution would be to let Gulp spawn a PHP process that displays a json encoded string of the configuration, pipe this to an injection module to inject it in a JavaScript file.
Any thoughts?
Not sure if it is going to work, that seems to me that you will still need to fire up an XMLHttpRequest to get it. One question tho, how are you deploying this in your production server?
Oh by the way, something just came out on top of my head, if AJAX is not an option, I used to do something like this after looking at my previous project, (this isn't very clean as well) :D
Include this "PHP" file and you should be able to have foo and bar setup in JavaScript.
<script type="text/javascript" src="http://mysite.com/js/example.js.php">
Inside example.js.php
<?php
header("content-type: text/javascript; charset: utf-8");
$bar = array('baz' => 1);
?>
var foo = 'bar';
var bar = <?php echo $bar['baz']; // which is 1?>
try
view()->share('config', json_encode($config));
then on your views, you can just
//js here
var config = {{$config}};
Hi @ChrisLahaye, see the following package from @JeffreyWay:
https://github.com/JeffreyWay/PHP-Vars-To-Js-Transformer
I think it is you are looking for.
Thanks for the replies.
Was hoping I could find a more static solution (e.g. via Gulp) so the request doesn't travels through PHP or the framework. I will just print the configuration in a template like suggested, at least this allows caching.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community