djangodjango-templatesleafletmaptiler

Difficulty passing a maptile as context directly into a Leaflet map tilelayer in Django


I have a web-page that has an embedded Leaflet map. I've managed to create a drop-down for the user to select different maptile types from Maptiler.com. This worked fine with the maptile address being passed as context from the view which was then specified in my template as follows:-

L.tileLayer('{{ context.maptileaddress }}', {attribution: '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>',}).addTo(map);

I then decided that I might like to use other maptile providers such as Stamen and that would require me to pass the whole tilelayer argument as follows:-

L.tileLayer('{{ context.maptilefullkey }}).addTo(map);

where a valid 'maptilefullkey' is:-

'https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.{ext}', {
            attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
            subdomains: 'abcd',
            minZoom: 1,
            maxZoom: 18,
            ext: 'png'
            }

When I embed this text literally into the tileLayer method, the maptile displays just fine - see my print.

The maptile works fine when it is hardcoded into the the tileLayer() method

You can also see that I have successfully passed {{ context.maptilefullkey }} to the template and it has printed at the bottom of the webpage successfully. It apparently matches the valid key exactly.

But when I pass it as a variable L.tileLayer({{ context.maptilefullkey }}).addTo(map);, the maptile completely disappears.

Why has this happened and how do I fix it?

Is the fact that the string ends in curly bracket and then precedes the double curly bracket that closes off the context creating a problem? Or is it the attribution that is causing an issue?

The help from this community is much appreciated!

Phil #anoobinneed


Solution

  • I have managed to work this out in the end. It's all part of me being fairly new to this.

    I needed to add the tag "safe" to where the fullkey is being picked up from:-

    L.tileLayer({{ context.maptilefullkey | safe }}).addTo(map);
    

    It worked previous when just the tileaddress was being passed but clearly the fullkey had an "unsafe" character or characters and I needed to instruct the template to pass the string exactly as it is.

    This is explained quite well in the documentation:-

    https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/

    I hope this may help someone in the future.

    Phil