最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

assign javascript variable to twig variable symfony 2 - Stack Overflow

programmeradmin1浏览0评论

I would like to assign the value of a Javascript variable to a twig variable like this :

$(".change-mod").click(function(){
   var id=$(this).attr("id");
   {{% set page =  'here i want to assign id to page' %}}
});

How can I do it?

I would like to assign the value of a Javascript variable to a twig variable like this :

$(".change-mod").click(function(){
   var id=$(this).attr("id");
   {{% set page =  'here i want to assign id to page' %}}
});

How can I do it?

Share Improve this question edited Nov 6, 2013 at 15:05 cheesemacfly 11.8k11 gold badges55 silver badges72 bronze badges asked Nov 6, 2013 at 14:43 SafwenSafwen 851 gold badge3 silver badges7 bronze badges 4
  • 2 Twig code is executed on the server. Javascript is executed on the client. You can't transfer data between them in this way. – lonesomeday Commented Nov 6, 2013 at 14:47
  • any suggestions in how to do it ? – Safwen Commented Nov 6, 2013 at 14:49
  • 1 Hard to say without knowing what your purpose is. The solution might be AJAX; it might be Javascript templates; it might be simple DOM manipulation; it might be a normal HTTP request. You're going to have to work out what best suits your purpose. – lonesomeday Commented Nov 6, 2013 at 14:54
  • Maybe by sending AJAX request but, needless to say, any Twig variable is volatile as it will expire at the end of the request... – Jovan Perovic Commented Nov 6, 2013 at 14:54
Add a ment  | 

3 Answers 3

Reset to default 3

It is simple not possible. These are two different things.

Javascript runs on client browser and TWIG templating system is generated on server.

You can replace generated HTML content by Javascript only on generated page or by AJAX request and your content from server response.

this my stupid solve

$(".change-mod").click(function(){
   var id=$(this).attr("id");
$.ajax({
         url: 'jstotwig.php',
         type: 'POST',
         data: {id: id},
       success: function(data) {
                var page =  "here i want to assign"+data+"to page"
                }
         });
});

Bare in mind, that it will not really allow you to assign javascript variables to twig variables, but it will allow you to generate paths on the client side as you can read here http://symfony./doc/current/book/routing.html#generating-urls , the documentation points to a bundle, that lets you do exactly that https://github./FriendsOfSymfony/FOSJsRoutingBundle , it may be even possible to assign javascript variables to twigs, but that is not what this bundle does.

发布评论

评论列表(0)

  1. 暂无评论