javascriptpythontemplatespyramidchameleon

How to use tal variable with javascript?


I want to pass a variable returned as a response to the zope template into a javascript variable in pyramid.

here's the views code :

def return_table(request):
selected = request.params.getall("selectedcategories")

return {'selected': selected}

and here's the template :

<script tal define:"selected ${selected}">
    var selected = ${selected}
    $.ajax({
        type:"POST",
        url: '/return_table.json?selectedcategories=' + selected,
        async: false,
        success: function (response) {
            console.log(response)
        }
   })
</script>

But this is not working. I want to pass the value of selected into the javascript variable.


Solution

  • The safest way is to pass variables as HTML5 data attributes, or in <meta> inside <head>.

    <script id="my-script" data-selected="${selected}">
        $(document).ready(function() {
    
            var selected = $("#my-script").attr("data-selected");
    
            $.ajax({
                type:"POST",
                url: '/return_table.json?selectedcategories=' + selected,
                async: false,
                success: function (response) {
                    console.log(response)
                }
           })
        });
    </script>
    

    More information about data attributes: http://caniuse.com/#feat=dataset

    You could also generate <script> snippet exposing variables as JavaScript globals like this and then read global variables directly in your JavaScript code:

    <script>
         window.myVar = "${selected}";
    </script>     
    
    <script>
         ... code goes here ...
    </script>
    

    ... but I do not recommend, as variables containing user input would open your site to attacks and escaping JavaScript variables inside HTML is difficult. It is handy though, if you need to pass several variables - you can use json.dumps() against a Python dictionary to generate a JavaScript object containing all your variables.