Search code examples
djangoleafletdjango-leaflet

specific leaflet layer style to change dynamically based on django tags


Potion of my html code do do style

<script type="text/javascript"> 
         function our_Layers (map, options){
            var datasets = new L.GeoJSON.AJAX("{% url 'owner' %}",{

                style: function colors(feature){                    
                    switch(feature.properties.lr){                        
                        case "{{LR}}":
                            return{
                                color: 'red'
                            };
                        break
                    }
                },

                onEachFeature: function(feature, layer){
                    //layer.bindPopup(feature.properties.lr.toString());
                    layer.bindPopup('<strong>LR No.: </strong>'+ feature.properties.lr.toString()
                   );
                }
            });
            datasets.addTo(map); 

         }
    </script>

    {% leaflet_map "parcels" callback="window.our_Layers" %}

my view in django

def Usermap(request):
    plots1 = request.user.person.Persona.all()

    for Registration in plots1:
        LR=(Registration.parcels.lr)            
    context = {'plots':plots1,'LR':LR}
    return render(request, 'Cadastre/Usermap.html', context)

Have used that for loop in django to show me available lr which are 3 but i cant use django for loop tags inside the leaflet function any help


Solution

  • I found a way to go around it..first i perform a for loop in django views and append my result in a list. example

    def Usermap(request):
        plots1 = request.user.person.Persona.all()
        LR =[]
    
        for Registration in plots1:
            LR.append(Registration.parcels.lr)            
        context = {'plots':plots1,'LR':LR}
        return render(request, 'Cadastre/Usermap.html', context)
    

    then do another loop in html to access the list items and use it to style my map dynamically. example

    <script type="text/javascript">
    datasets = new L.GeoJSON.AJAX("{% url 'Plots' %}",{
     style: function colors(feature){
         var LRS = {{LR|safe}};
         var x;
         for (x of LRS){                    
             switch(feature.properties.lr){                        
                case x:
                     return{
                        color: 'red'
                     };
                break
             }
          }                        
     },
        onEachFeature: onEachFeature
    }).addTo(map);
    </script>
    

    I hope this help someone with same issue since there is no other answer thank you.