[英]how to use symfony controller variables in frontend js?
Say I have a controller like this: 说我有一个像这样的控制器:
public function showAction(Request $request, $id, $context = array())
{
$url = $this->getPlayUrl($id, $context);
//some code here}
I want to use the variable $url in a frontend js file like this : 我想像这样在前端js文件中使用变量$ url:
var html = '<iframe src=\''+ url +'\' name=\'viewerIframe\' id=\'viewerIframe\' width=\'100%\'allowfullscreen webkitallowfullscreen height=\'100%\' style=\'border:0px\'></iframe>';
How am I supposed to make this happen? 我应该如何做到这一点? For the code above ,it gave me 'undefined url' error. 对于上面的代码,它给了我“未定义的网址”错误。
Thank you. 谢谢。
In you view add some script tags and assign a javascript vraible to the twig variable. 在您的视图中,添加一些脚本标签,并将JavaScript可变变量分配给twig变量。 Don't forget to quote the twig (if required). 不要忘了引用树枝(如果需要)。
Firstly, I would ensure that the $url always had a value; 首先,我将确保$ url始终具有值;
return $this->render('MyWebBundle:Player:show.html.twig', array(
'file' => $file,
'url' => (empty($url)) ? '' : $url,
'context' => $context,
'player' => $player,
'agentInWhiteList' => $agentInWhiteList
));
Something like; 就像是;
<script>
var jsVar = '{{ url }}';
var html = false;
if (jsVar.length > 0) {
html = '<iframe src=\''+ jsVar +'\' name=\'viewerIframe\' id=\'viewerIframe\' width=\'100%\'allowfullscreen webkitallowfullscreen height=\'100%\' style=\'border:0px\'></iframe>';
}
// test html !== false before using it
</script>
如果您使用HTML5数据属性,则可能会更好: https : //developer.mozilla.org/zh-CN/docs/Web/Guide/HTML/Using_data_attributes
Another option would be to have your template call a controller action (so you can pass parameters as required), for example, like this example for using highchart.js: 另一个选择是让您的模板调用控制器动作(以便您可以根据需要传递参数),例如,如以下使用highchart.js的示例所示:
{% block javascripts %}
{{ parent() }}
<script src="/js/highcharts.js"></script>
<script src="/js/exporting.js"></script>
<script type="text/javascript">
{{ render(controller('AppBundle:Default:script')) }}
</script>
{% endblock %}
In the controller it looks like this: 在控制器中,它看起来像这样:
public function scriptAction() {
$reports = $this->get('app.reports');
$chart = $reports->getDistsFYToDate();
return $this->render('Default/script.js.twig', array(
'chart' => $chart,
));
}
and script.js.twig
looks like this: 和script.js.twig
看起来像这样:
$(document).ready(function () {
var options = {
chart: {
type: 'line'
},
title: {
text: 'Distributions, FY{{ chart.fy }} to date'
},
xAxis: {
categories: [{% for category in chart.categories %}{{category|raw}}{%endfor%}]
},
yAxis: {
title: {
text: 'Distributions'
}
},
series: {{ chart.series|raw }}
};
$('#linechart').highcharts(options);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.