简体   繁体   中英

How to pass parameter to js function from template parameter array

I generated in tornado template table with cities and I am trying to have like last column details button

{% if globals().has_key('results')  %}
   {% for result in results %}
     <tr>
         <td>{{result['name']}}</td>
         <td>{{result['citizens']}}</td>
         <td style="width:100px; height:100px;">
          <div class="ui-grid-b">
          <a class="ui-block-a ui-icon-detail" onclick="showDetails('{{id}}',{{result['city_id']}});" data-role="ui-li-aside" data-icon="right_arrow" data-theme="a"></a>
          </div>
         </td>
     </tr>
    {% end %}
{% end %}

and on click to load on another page with parameters in url.

<script type="text/javascript">
    function showDetails(id, city_id)
       {
          window.location = '/cities?id='+id+'&city_id='+city_id;
        }
</script>

How to pass parameters to show details function ? (I cannot use ', I tried with \\" but it doesn't work). Results is list of dictionaries with keys name, citizens, city_id. {{ }} is used by tornado template to access passed parameter.

   showDetails = function (id, city_id)
       {
          window.location = '/cities?id='+id+'&city_id='+city_id;
        }

I think is the easy way

The variable inside the braces will be output directly (or, the string representation of it), so it depends what it is set to.

eg if you have:

id = 'foo'
results = [{ 'city_id': 'bar' }]

and you are passing them to the template, then this line:

showDetails('{{id}}',{{result['city_id']}});

will be output as follows (you can confirm this with view source):

showDetails('foo',bar);

I'm guessing you're missing the quotes around {{result['city_id']}} , unless result['city_id'] is an integer, in which case it should work. Single or double quotes are both fine in JavaScript.

However, as @Pete already pointed out, "on click to load on another page with parameters in url" is what we have the href attribute for. You can save yourself a lot of work and potential brokenness with:

<a href="/cities?id={{ id }}&city_id={{ result['city_id'] }}" ....></a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM