[英]Passing data from Django views/template into the static javascript
這個問題已經以多種方式被問到,但是諸如在腳本標簽之前定義變量之類的解決方案沒有奏效。
模板.html
<script>
var locations = {{ some_variable }}
</script>
<script type="text/javascript" src="{% static 'base/scripts/maps.js' %}"></script>
我相信這是因為maps.js
實際上是一個函數。 它的開頭是這樣的:
地圖.js
(function($){
"use strict";
function mainMap() {
var ib = new InfoBox();
// Infobox Output
function locationData(locationURL,locationImg,locationTitle, locationAddress, locationRating, locationRatingCounter) {
return('SOME_HTML_WITH_VARIABLES')
}
// Locations
var locations = [
[ locationData('listings-single-page.html','images/listing-item-01.jpg',"Tom's Restaurant",'964 School Street, New York', '3.5', '12'), 40.94401669296697, -74.16938781738281, 1, '<i class="im im-icon-Chef-Hat"></i>'],
];
我想要做的是從我的模型中傳遞位置數據,例如
{% for model in query_list %}
[ locationData('link_to','img_url','{{ model.name }}','{{ model.address }}', '5', '10'), {{ model.latitude }}, {{ model.longitude }}, {{ forloop.counter }}, '{{ model.icon }}'],
{% endfor %}
可能的解決方案:
將整個maps.js
文件發布到 template.html 中的腳本標簽內。 但是這個文件有 10000 多行。
這不是一個精確的解決方案,但它是處理這種情況的一個技巧。
視圖.py
def index(request):
monthList = ['jan', 'feb', 'mar]
activities = [1,2,3]
model = {"name" : "Fine Guy" ]
context = {
'monthList' : monthList,
'activities' : activities,
'model' : model,
}
return render(request, 'index.html', context)
索引.html
<!-- passing django values to external js -->
<!-- hided -->
<input type="text" id="monthList" style="display: none" value="{{ monthList|safe }}">
<input type="text" id="activities" style="display: none" value="{{ activities|safe }}">
<!-- for your question -->
<input type="text" id="modelname" style="display: none" value="{{ model.name|safe }}">
在這里,我只是將值列表monthList
和activities
從 django 上下文傳遞到呈現的 HTML 文件,並使用(style="display:none")
隱藏它
|safe
是為了從 Python 格式到 Javacript 格式的准確值
現在,您可以使用index.html中的標簽 Id獲取static/external.js中的值
外部.js
var monthList = document.getElementById("monthList").value;
var activities = document.getElementById("activities").value;
// for your question
var modelname = document.getElementById("modelname").value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.