我需要動態插入標記數據(名稱,緯度,長)到javascript,maps.js
。Django 1.11:動態JavaScript加載谷歌地圖標記
在我maps.js,我目前有:
var locations = [
[ locationData('listings1.html','images/listing-item-01.jpg',"listing name",'Address ', '4.5', '12'), 40.94401669296697, -74.16938781738281, 1, '<i class="im im-icon"></i>'],
[ locationData('listings2.html','images/listing-item-02.jpg','Name2','Place', '5.0', '23'), 40.77055783505125, -74.26002502441406, 2, '<i class="im im-icon"></i>'],];
,我需要能夠例如加載這個動態使用for循環
{% if listings %}
var locations = [
{% for listing in listings %}
[ locationData({{ listing.url}} , {{ listing.name }} , {{ listing.place }}) ],
{% endfor %}
]
目前,我有一個maps.js靜態文件,這是我使用加載:
<script type="text/javascript" src="{% static 'scripts/maps.js' %}"></script>
我不能插入標籤那裏,因爲它是靜態調用。 然而,由於maps.js
是static
,我無法加載的標籤如{{ listing.location }} , {{ listing.lat }} , {{ listing.lng }}
等
我試圖2種溶液(和在註釋中描述的一個)。
1)我試着加載一個小
#template.html
<script>
var locations =
// python code
</script>
但這並沒有工作,我想是因爲locationData
是一個功能,這也是在maps.js.定義
我可能包含整個maps.js
在template.html
,但它是230行代碼。
2)我嘗試添加maps.js
我users
app文件夾,像這樣:
users/templates/users/maps.js
而且裏面那個js的我裝上面定義模板標籤。在我的views.py中,我做了:
def index(request):
js_file = "users/templates/users/maps.js"
return render(request, "users/template.html", context={"js_file": js_file })
#template.html
<script src="{{js_file}}"></script>
但是,我收到文件無法找到的錯誤。
我試着這樣做,在我定義了var位置模板,只需從maps.js複製粘貼代碼以在maps.js之外定義變量。然後我評論了地圖。js var位置,但這不起作用 – Roma
此解決方案應該可行,我只以這種方式解決了我的這些問題。看看我的這個答案,https://stackoverflow.com/a/46302661/4834455你可能會從這個更多的線索。 –
做完這些之後,我可以看到這隻適用於1項。但是,如何將循環加入此?我需要maps.js文件具有與我的模型返回的條目數相同數量的位置(標記) – Roma