Use js variables in twig and js variables in twig
This article describes how to use js variables in twig. We will share this with you for your reference. The details are as follows:
First read a piece of code
<script type="text/javascript"> jQuery(document).ready(function(){ jQuery(#my_input).change(function(){ var value = jQuery(#my_input).val(); jQuery.ajax({ url: {{ path('ParteAccidentes_ajax', {'emergencia': value}) }}, timeout: 5000, success: function(data) { alert('ok'); }, error: function() { alert('mal'); } }); }); });</script>
The address of this ajax request cannot be accessed normally.
In this Code, the value of jQuery ("# my_input"). val () is assigned to the value, and then you want to introduce the value variable to the url address in ajax.
At this time, you will find that the value of the address you access is not introduced, but is processed as a string.
That is to say, the js value cannot be directly referenced in twig.
The reason is that twig parses php variables while value is js variables, so twig is considered a string by default.
Therefore, replace must be used for replacement.
The Code is as follows. You can compare it with the above Code:
<script type="text/javascript"> jQuery(document).ready(function(){ jQuery(#my_input).change(function(){ var value = jQuery(#my_input).val(); var url = "{{ path('ParteAccidentes_ajax', {'emergencia': 'text'}) }}"; url = url.replace("text", value); jQuery.ajax({ url: url, timeout: 5000, success: function(data) { alert('ok'); }, error: function() { alert('mal'); } }); }); });</script>
Permanent address: http://blog.it985.com/7020.html
This article is from the IT985 blog. Please indicate the source and relevant links when reprinting.