简体   繁体   English

从Symfony2中的JavaScript访问PHP变量

[英]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. 我正在使用Symfony2-绘图工具是纯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. 因此,一旦用户到达工具加载的页面,javascript就需要知道用户先前输入的一些数据(例如画布的高度和宽度),这些数据已通过表格发送给控制器。 I have no problem using the variables in the templates, but can't access them with the javascript files. 我在模板中使用变量没有问题,但是无法使用javascript文件访问它们。

Is there a way to set javascript variables in a template? 有没有办法在模板中设置javascript变量?

I've included the javascript file in the template like so (which works): 我已经在模板中包含了javascript文件,如下所示(有效):

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

Just put some script tags in your template and output the variable into them using PHP. 只需在模板中放置一些脚本标签,然后使用PHP将变量输出到它们中即可。 It could look similar to this: 它看起来可能类似于:

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

Can't you just print the variable with php in the page? 您不能只在页面中用php打印变量吗? something like 就像是

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

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM