Adding external javascript library available to all pages with query string value came from PHP in Drupal 8

In Drupal 7, adding external javascript library available to all pages with query string value came either from PHP computed value or from database this can be done by:

  
/**
 * Implements hook_init()
 */
function mymodule_init() {
  drupal_add_js('//maps.googleapis.com/maps/api/js?key=' . variable_get('mymodule_google_map_api_key', NULL), 'external');
}
  

For Drupal 8 this is possible by:

  
/**
 * Implements hook_page_attachments().
 */
function mymodule_page_attachments(array &$page) {
  $config = \Drupal::config('mymodule.settings');
  $apiKey = $config->get('google_map_api_key');
  $page['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag'  => 'script',
      '#attributes' => ['src' => "//maps.googleapis.com/maps/api/js?key=$apiKey"],
    ],
    'mymodule_google_map_lib',
  ];
}
  

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.