[英]Symfony2 pass variable from controller to javascript
我有這個controller.php
$repository = $this->getDoctrine()->getManager()->getRepository('TechappStatsBundle:ParentForm');
$data = $repository->findBy(array(),array('id' => 'desc'),1,0);
$formulaire = new ParentForm();
$parent= $this->get('form.factory')->create(new ParentFormType(),$formulaire);
if ($parent->handleRequest($request)->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($formulaire);
$em->flush();
}
return $this->render('TechappStatsBundle:Stats:index.html.twig',array("res" => $data,
"parentform"=>$parent->createView(),));
我想用js檢查視圖中的變量res
是否等於特定值,但我不知道如何傳遞它。
您可以像這樣通過控制器傳遞參數:
return $this->render('TechappStatsBundle:Stats:index.html.twig', array(
"res" => "Your data here"));
您可以像這樣訪問index.html.twig中的“ res”參數:
{% block js %}
<script type="text/javascript">
var res = '{{ res }}';
alert(res);
</script>
{% endblock %}
我的選擇始終是將其發送到data-value ,
你可以做類似的事情
<div id="res-result" data-res="{{ res }}" style="display: none;">
div不需要隱藏,即使它與div有關,我也總是將其放在與div有關的內容中,即使它不是隱藏的也是如此
然后從Jquery:
resValue = $('#res-result').data('res');
將JS文件放在HTML之外是IMO最干凈的方法
如果要將數據傳遞給Javascript,可以將視圖更新為以下任意一種:
data-<field>
一旦獲得它,就可以輕松地從jQuery
獲取值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.