简体   繁体   中英

Passing data from Django views/template into the static javascript

This question has been asked in multiple ways , however the solutions such as defining variables before the script tag haven't worked.

template.html

<script>
    var locations = {{ some_variable }}
</script>
<script type="text/javascript" src="{% static 'base/scripts/maps.js' %}"></script>

I believe this is because maps.js is actually a function. The start of it is as follows:

maps.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>'],

       ];

What I want to do is to pass location data from my model eg

  {% 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 %}

Possible solution:

Post the whole maps.js file in the template.html, inside the script tag. But this file has 10000+ lines.

This is not an exact solution, but it is a trick to handle the situation.

views.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)     

index.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 }}">

Here, I just pass the list of values monthList and activities from the django context to the rendered HTML file, and I hide that using (style="display:none")

|safe is for accurate value from the Python format to the Javacript format

Now, you can get the values in static/external.js using the tag Id from index.html

external.js

var monthList = document.getElementById("monthList").value;
var activities = document.getElementById("activities").value;

// for your question
var modelname = document.getElementById("modelname").value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM