Как передать переменную ENV в тег скрипта

Я пытаюсь передать мой ключ API, который находится в моем файле application.yml, в тег сценария js для карт Google, это возможно? Если нет, каков наилучший способ справиться с этим? Также я использую драгоценный камень Figaro для хранения переменных ENV. Заранее спасибо.

    <% if @location.latitude.present? && @location.longitude.present? %>
  <script>
    var myLatLng = {lat: <%= @location.latitude %>, lng: <%= @location.longitude %>};
    function initAutocomplete() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: myLatLng,
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: '<%= @location.name %>'
    });

    // Create the search box and link it to the UI element.
    var input = document.getElementById('pac-input');
    var searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener('bounds_changed', function() {
      searchBox.setBounds(map.getBounds());
    });

    var markers = [];
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', function() {
      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }

      // Clear out the old markers.
      markers.forEach(function(marker) {
        marker.setMap(null);
      });
      markers = [];

      // For each place, get the icon, name and location.
      var bounds = new google.maps.LatLngBounds();
      places.forEach(function(place) {
        var icon = {
          url: place.icon,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25)
        };

        // Create a marker for each place.
        markers.push(new google.maps.Marker({
          map: map,
          icon: icon,
          title: place.name,
          position: place.geometry.location
        }));

        if (place.geometry.viewport) {
          // Only geocodes have viewport.
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
    map.fitBounds(bounds);
  });
}
  </script>
  <input id="pac-input" class="controls" type="text" placeholder="Search Box">
  <div id="map"></div>
  <script src="https://maps.googleapis.com/maps/api/js.erb?key=MAPS_API_KEY&libraries=places&callback=initAutocomplete"
         async defer></script


<% end %>

ошибка

https://maps.googleapis.com/maps/api/js.erb?key=&libraries=places&callback=initAutocomplete

Это то, что у меня есть, и это дает мне ошибку, которую я написал, если я вставлю Ключ непосредственно, он работает.

<script src="https://maps.googleapis.com/maps/api/js.erb?key=<%= ENV['MAPS_API_KEY'] %>&libraries=places&callback=initAutocomplete"
         async defer></script

6 ответов

Это сработало для меня:

<script async defer src=<%="https://maps.googleapis.com/maps/api/js?key=#{ENV['GOOGLE_MAPS_API_KEY']}&callback=initMap"%> type="text/javascript"></script>

Попробуй это #{ENV['MAPS_API_KEY']}У меня была похожая проблема раньше:

<script src="https://maps.googleapis.com/maps/api/js.erb?key=<%=#{ENV['MAPS_API_KEY']}%>&libraries=places&callback=initAutocomplete" async defer></script>

Вы должны быть в состоянии обработать это как любую другую переменную ENV, используя ERB:

...
<script src="https://maps.googleapis.com/maps/api/js.erb?key=<%=ENV['MAPS_API_KEY']%>&libraries=places&callback=initAutocomplete"
         async defer></script>

Я полагаю, вы просто не хотите помещать свой api_key в HTML-тег и сделать ваш ключ уязвимым. Вы можете попробовать следующий код под вашим index.html, он работает для меня.

<div id="google">
  <script type="text/javascript">
    import {
      GOOGLE_MAP_API
    } from "<the location you save your apikey>";

    function changeSrc() {
      document.getElementById("google").src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAP_API}`
    }
  </script>
</div>

Обратите внимание: если вы не используете Ruby (или Figaro) и используете Webpack, вы можете ввести его через HtmlWebpackPlugin.

Вы можете использовать тег данных для передачи переменных env

      <script id="div" data-key="<%=ENV['MAPS_API_KEY']%>">
  const div = document.getElementById("div");
  console.log(div.dataset.key);
</script>
Другие вопросы по тегам