简体   繁体   English

从 django settings.py 访问 API 密钥以获取模板中的脚本标记 src

[英]Accessing API Key from django settings.py for script tag src in template

I am trying to add my api key from my settings.py to to the src for my script tag.我正在尝试将我的 api 密钥从我的 settings.py 添加到我的脚本标签的 src 中。 I have been unsuccessful, so I'm hoping someone has an idea I haven't thought of or found online.我一直没有成功,所以我希望有人有一个我没有想到或在网上找到的想法。

<script>
    let GOOGLE_API_KEY='{{GOOGLE_API_KEY}}'
    console.log(GOOGLE_API_KEY) </script> 
<script
      src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY&callback=initMap&libraries=&v=weekly"
      async defer>
</script>

GOOGLE_API_KEY successfully logs the correct api key from my views.py GOOGLE_API_KEY 从我的 views.py 中成功记录了正确的 api 密钥

This doesn't work because of the async nature of js.由于 js 的异步特性,这不起作用。

Try the following:尝试以下操作:

<script
      src="https://maps.googleapis.com/maps/api/js?key={{GOOGLE_API_KEY}}&callback=initMap&libraries=&v=weekly"
      async defer>
</script>

I found a solution on geeksforgeeks我在 geeksforgeeks 上找到了解决方案

<!-- Manipulating script tag to use django secret key -->
<!-- https://www.geeksforgeeks.org/how-to-insert-a-javascript-variable-inside-href-attribute/ -->

<script>
    let GOOGLE_API_KEY='{{GOOGLE_API_KEY}}'
    console.log(GOOGLE_API_KEY)
</script>
<script> 
    var loc = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&callback=initMap&libraries=&v=weekly`; 
    document.write('<script src="' + loc + '"><\/script>'); 
</script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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