enp4yne
enp4yne

Reputation: 646

Accessing php variables from javascript in Symfony2

I am developing a small drawing tool which collects some data from the user before starting the tool. I'm using Symfony2 - the drawing tool is pure javascript.

So once the user reaches the page where the tool loads, javascript needs to know about some of the data the user has entered previously (for example height & width of the canvas), which have been sent to the controller by forms. I have no problem using the variables in the templates, but can't access them with the javascript files.

Is there a way to set javascript variables in a template?

I've included the javascript file in the template like so (which works):

<script type="text/javascript" src="<?php echo $view['assets']->getUrl('bundles/mybundle/js/myjs.js') ?></script>

Upvotes: 0

Views: 631

Answers (2)

Gabber
Gabber

Reputation: 5472

Can't you just print the variable with php in the page? something like

<script type="text/javascript">
    var t=<?php echo $var; ?>

</script>

Upvotes: 1

Mike Brant
Mike Brant

Reputation: 71422

Just put some script tags in your template and output the variable into them using PHP. It could look similar to this:

<script type="text/javascript">
var canvasHeight = <?php echo $canvasHeight; ?>;
var canvasWidth = <?php echo $canvasWidth; ?>;
</script>

Upvotes: 3

Related Questions