Search code examples
javascriptgoogle-maps-api-3python-3.7django-2.2

template tag 'url' is not working if using outer javascript


I creating a django program using 'google-map api'.
'mapinit(json-data)' is read from 'map.js'

<body onload="mapinit('{{ data }}')">

    <!-- create a map area with shop information -->
    <div class="wrapper">
        <div id="shopinfomation"></div>
        <div id="map_canvas1" style="width: 500px; height: 500px"></div>
    </div>

    <!-- post action from html is ok! -->
    <h3>category 1</h3>
    <form class="specific_form" action="{% url 'index_search' '1A' %}" method="POST">
        {% csrf_token %}
        <input type="submit" class="btn-flat-border" value="ramen" /> search ramen shops
    </form>

outer javascript have some action such as ajax, redirect.
Right now I am writing the url directly.

// get a shop detail
$.ajax({
    type: "POST",
    url: "/gmarker/search/detail/" + json.shops[i]['place_id'],
    beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", Cookies.get('csrftoken'));
    }
}).done(function(data){
    shopinfomation.innerHTML = 'ajax success. shop information...';
}).fail(function(){
    shopinfomation.innerHTML = 'ajax error.';
});

I want using this.

console.log("{% url 'index_search' '2' %}")

I want.

/gmarker/search/2

but chrome output is ... Come is same one.

{% url 'index_search' '2' %}
urlpatterns = [
    path('', views.index, name='index'),
    path('search/<str:searchcode>', views.index, name='index_search'),
    path('search/detail/<str:place_id>', views.searchdetail, name='detail_search'),
    path('result/<str:searchcode>', views.index, name='index_result'),
]

outer javascript is can't read template tag??


Solution

  • Yes, external javascript cannot use template variables. What you need to do is to send data from internal javascript like. In mymap.html

    <script>
        var TemplateVar = {
            my_url: "{% url 'index_search' '2' %}"
        }
    </script>
    <script src="{% static 'js/map.js' %}"></script>
    

    Now, in map.js

        my_url = TemplateVar.my_url;      // Taking json attribute from script of mymap.html
        console.log(my_url);              // You should get what you are expecting
    

    Extra: You may need to escape variables to prevent some attacks