簡體   English   中英

如何從 django 模板中的 js 腳本向 {% url tag %} 插入值

[英]How to insert value to {% url tag %} from js script inside django template

我在 Django 模板中使用 leaflet JS。 我想在 map 上顯示標記,其中緯度和經度是從查詢集中獲取的。 我發現我可以通過視圖發送查詢集,然后使用 Django 模板語言在內部使用它來將緯度設置為特定的標記。 我想在標記的彈出窗口中有一個圖像,我的問題來了。 我知道我不能使用 JS,因為它是客戶端,而 Django 模板是服務器端,但是如何解決您想要動態創建標記並使用數據庫中的圖像彈出窗口的情況。 我應該使用 AJAX 來做到這一點嗎?

我的看法:

class MapView(ListView):
    template_name = 'map.html'
    model = Post
    queryset = serialize('json', Post.objects.all(), fields = ['lat','lon', 'image'])

和模板,下面的 for 循環是 marker1,其中 popup 是硬編碼的並且可以正常工作:

var map = L.map('map').setView([49.175573,20.072700], 11);
    
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

var post_base = {{object_list|safe}}
    
    for (let index = 0; index < post_base.length; index++) {
        console.log(post_base[index]['fields']['lat']);

        var image_path = post_base[index]['fields']['images']
        marker = new L.marker([post_base[index]["fields"]["lat"],post_base[index]["fields"]["lon"]]).addTo(map)
        .bindPopup("<img style=10%; src={% static 'images/????????????????????????'%}/>");
    }

marker1 = new L.marker([49.295236, 20.413089],{opacity:0.5}).addTo(map)
    .bindPopup("<img src={% static 'images/lomnica_image.jpeg' %}/>");

</script>

任何人都可以解釋什么是解決它的正確方法嗎? 謝謝

嗨,您是絕對正確的,如果沒有構建器或 webpack、parcel 等,您將無法在服務器端執行您的 js 代碼。

So if you decide to render marker runtime with client side your probably need to try django REST framework that provide a lot of tools for creating REST API like serializers and viewsets.

但是當然您仍然可以使用本機 Django 使用Django 序列化器輕松進行數據序列化

您也可以使用此存儲庫作為啟動示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM