我需要动态插入标记数据(名称,纬度,长)到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