Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

298
Visualizações
Django template JS variable 'safe' method not passing data to custom js file?

I'm trying to pass a google api key into my custom js file in Django, the function is for a AutoComplete google places api search , but at the moment it's not working, if I put the actual key directly into the .getScript function, like:

https://maps.googleapis.com/maps/api/js?key=XXX&libraries=places"

then the search function works, but with the current setup also intended to hide the api key, it doesn't work, I'm obviously missing something, appreciate any ideas?

django settings:

GOOGLE_API_KEY = "XXX"

base.html

<script src="{% static 'js/google_places.js' %}"></script>

views.py

{'google_api_key': settings.GOOGLE_API_KEY} 

google_places.js

$.getScript("https://maps.googleapis.com/maps/api/js?key=" + google_api_key + "&libraries=places")
.done(function( script, textStatus ) {
    google.maps.event.addDomListener(window, "load", initAutoComplete)
})



let autocomplete;

function initAutoComplete(){
   autocomplete = new google.maps.places.Autocomplete(
       document.getElementById('autocomplete'),
       {
           types: ['country', 'locality'],
       })
}

travel.html

{% extends 'base.html' %}
{% load static %} 

<input id='autocomplete' placeholder='enter a place' type="text">

{% endblock content %}
    
    
{% block js %}
    
        
<script type="text/javascript">
    
   var google_api_key = "{{google_api_key|safe}}";
    
</script>
        
    
    
{% endblock js %}

also the google_api_key variable is being passed into travel.html , I've checked that and it's working fine.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try the json_script tag as described in Django docs https://docs.djangoproject.com/en/4.0/ref/templates/builtins/

in your template:

{{ google_api_key|json_script:"google_api_key" }}

then in the js before you want to use google_api_key:

const google_api_key = JSON.parse(document.getElementById("google_api_key").textContent);
about 4 years ago · Juan Pablo Isaza Relatório

0

I figured out the problem I was having, I needed to put the document ready function in my custom js file, so in the end I went with the json_script method and this is what I have now:

travel.html (inserted into the html part of template above endblock content)

{{ google_api_key|json_script:"google_api_key" }}

google_places.js

$( document ).ready(function() {
    // const google_api_key = document.getElementById('google_api_key');
    const google_api_key = JSON.parse(document.getElementById("google_api_key").textContent);
    $.getScript("https://maps.googleapis.com/maps/api/js?key=" + google_api_key + "&libraries=places")
    .done(function( script, textStatus ) {
        google.maps.event.addDomListener(window, "load", initAutoComplete)
    })


    let autocomplete;

    function initAutoComplete(){
    autocomplete = new google.maps.places.Autocomplete(
        document.getElementById('autocomplete'),
        {
            types: ['country', 'locality'],
        })
    }

});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda