Home > Article > Backend Development > How to use js variables in twig, twig uses js variables_PHP tutorial
The example in this article describes the method of using js variables in twig. Share it with everyone for your reference, the details are as follows:
Look at a piece of code first
<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 requested by this ajax cannot be accessed normally.
In this code, the value of jQuery("#my_input").val() is assigned to value, and then I want to introduce the value variable into the url address in ajax.
At this time, you will find that the value of the address you visited is not introduced, but is treated as a string.
That is to say, the value of js cannot be directly referenced to twig.
The reason is that twig parses php variables, and value is a js variable, so twig thinks it is a string by default.
So we need to replace, so we need to use replace
The code is as follows, you can compare it with the code above:
<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>
The permanent address of this article: http://blog.it985.com/7020.html
This article comes from IT985 Blog. Please indicate the source and corresponding link when reprinting.
Readers who are interested in more content related to PHP templates can check out the special topics of this site: "Summary of PHP Template Technology", "Basic Tutorial for Getting Started with Smarty Templates", "Introductory Tutorial for Codeigniter" and "Introductory Tutorial for ThinkPHP"
I hope this article will be helpful to everyone in PHP programming.