django: how to pass template variable to javascript onclick routine?

15,914

Solution 1

If you are passing a coordinate, most probably you have a tuple consisting of latitude and longitude. You must separate them while passing to the Javascript function.

You may try this:

<div onclick=init_map({{ variables.0 }}, {{ variables.1 }})> 

Solution 2

This works

<div onclick="myFunction('{{ myVar }}')">

The only thing is that your myVar will become a string,

So if you need it as an object, an array... that's not what you need.

Solution 3

My solution:

  1. create button pass this below properties
    <button type="button" onclick="check(varsize = '{{ size.sizeDes}}' ); return false type="btsize">`
    
  2. write script on header part
    {% block javascript %}
    <script>
    function check(varsize) {
        document.getElementById("sizeid").value = varsize;
    }
    </script>
    {% endblock %}
    

Solution 4

I would suggest avoiding the html onclick() completely. You can pass your template variable {{ variables }} to the javascript function in an external script and then add an event listener (click) to execute a function upon clicking the left column. This allows you to use {{ variables }} anywhere in the script and it only required a single definition in your HTML rather than having to pass that in as an onclick() parameter each time you may need it (if that applies to your situation). Even if that's not the case it's still a better practice to separate the page logic (javascript) from its structure (html) as much as possible.

For example to use a template variable in an external script you need to declare the variable in your django template between a script tag like so:

<script>
   var myVariables = {{ variables }};
</script>

You can then use myVariables in your external script if it's loaded after you declare myVariables like so:

<script src="myExternalScript.js"></script>

In that script you can add a click event handler that may look like:

document.getElementById("leftBlockDivId").addEventListener("click", function() {
    init_map(myVariables);  // see how we can use myVariables here since it's already been declared
}, false);

The above event handler would be even simpler to write if you were to use jQuery where you could do something like:

$('#leftBlockDivID').click(function(){
    init_map(myVariables);
});

Solution 5

You can also pass your variables into data- attributes:

<div data-variables="{{ variables }}">

or even:

<div data-latitude="{{ variables.0 }}" data-longitude="{{ variables.1 }}">

and map pure javascript listener for clicking that html element, in which you will retrieve those data attributes. It lets you avoid using onclick= and passing it to external script directly or creating an <script> element to retrieve that data.

Share:
15,914

Related videos on Youtube

rubinlululu
Author by

rubinlululu

Updated on June 04, 2022

Comments

  • rubinlululu
    rubinlululu almost 2 years

    The concept comes from this http://www.prepbootstrap.com/bootstrap-template/real-estate-list-map-dynamic

    I enable 2 blocks in a django template, left blockshows device info (device name and location info),right block shows device map location.When user can click on left panels, the right map will change by passing Django template variable to Javascript routine. It seems the passed variable is not accepted by init_map.

    when user click on left column, the right map will switch according to latlon, which is passed by onclick routine.

    template page is as follows:

    {% block content %}
    {% for device in devices %}  
    <div class="col-xs-6 col-sm-6 col-md-4 col-lg-4 ">    
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 ">
            <div class="panel panel-default"  onclick="init_map( {{ device.coordinates.latitude }}, {{device.coordinates.longitude }} );return false;">
                <div class="row padall">                
                    <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3">
                        <span></span>                                                           
                        <img src="{{ device.thumbnail.url }}">
                    </div>
                    <div class="col-xs-12 col-sm-12 col-md-9 col-lg-9">
                        <div class="clearfix">
                            <div class="pull-left">
                                <span class="fa fa-dollar icon">{{device.name}}</span>
                            </div>
                            <div class="pull-right">
                                {{device.coordinates  }} 
                            </div>
                        </div>
                        <div>
                            <h4><span class="fa fa-map-marker icon"></span>{{ device.coordinates }}</h4>
                            <span class="fa fa-lock icon pull-right">{{  device.coordinates  }}</span>
                            {% with lat_lon=device.coordinates %}       
                             new is   {{ lat_lon }}
                            {% endwith %}
                            </div>                 
                        </div>
                    </div>
                </div>
            </div>
       </div>
    </div>
    
    <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
        <div class="row padbig">  
            <div id="map" class="map"></div>       
        </div>
     </div>
     {% endfor %}
     {% endblock content %}
    
    
    
    {% block extra_js %}
    <script type="text/javascript"  src="http://webapi.amap.com/maps?v=1.3&key=a23b5e94cecc8e98acd039aba6cd064c"></script>  
    <script type="text/javascript">
      var lat_lon  = {{ device.coordinates | js  }};  
    function init_map(lat,lon) {
    
        var imageLayer = new AMap.ImageLayer({
        url:'http://developer.amap.com/wp-content/uploads/2014/06/dongwuyuan.jpg',
            bounds: new AMap.Bounds(  
                new AMap.LngLat(116.327911, 39.939229),
                new AMap.LngLat(116.342659, 39.946275)),
    
            zooms: [15, 18] 
      });
        var map = new AMap.Map('map',{
               resizeEnable: true,
    
           scrollWheel: true,
    
           doubleClickZoom: true, 
           layers: [
               new AMap.TileLayer(),
               imageLayer
           ],
    
           view: new AMap.View2D({
               //center: new AMap.LngLat(116.342659, 39.946275),
              center: new AMap.LngLat(lat,lon),
               zoom:15
           })
          });  
        }
        //init_map(0);    
    </script>
    {% endblock %}
    

    if I enabled "center: new AMap.LngLat(116.342659, 39.946275)," the map will show up, while with "center: new AMap.LngLat(lat,lon)," , no map show up.

  • rubinlululu
    rubinlululu about 9 years
    the right column does not show when I removed the onclick routine.
  • alacy
    alacy about 9 years
    @rubinlululu I'm assuming you added the event listener in your script and included the actual id name for the left column div? Have you looked at the browser console to see if you have any errors? Also, try var myVariables = "{{ variables }}". Notice the quotes around {{ variables }}.
  • rubinlululu
    rubinlululu about 9 years
    I add 2 lines to javascript as follows, then the lat and lon are accepted, Thanks a lot for your nice help! function init_map(lat,lon) { var lat_float = parseFloat(lat); var lon_float = parseFloat(lon);