Need to add a JS file into  using a custom module with custom twig template I have created a custom module and created a config page which we need to input the url on that page.

Created a twig template within my custom module: 

&lt;script src={{ js_file_url }}&gt;test&lt;/script&gt;


In my .module file 

&lt;?php

/**
 * @file
 * Add the url to the header section.
 */

/**
 * Implments hook_page_attachments_alter().
 */
function custom_module_page_attachments_alter(array &amp;$attachments) {

  $js_file_url = \Drupal::config(' custom_module.settings')-&gt;get('url');

  $renderable = [
    '#theme' =&gt; 'my_template',
    '#test_var' =&gt; 'test variable',
  ];

$attachments['#attached']['html_head'][] = [
    [
      '#theme'  =&gt; 'my_template',
      '#js_file_url'   =&gt; $js_file_url,
    ],
  ];  

}


function  custom_module_theme($existing, $type, $theme, $path) {
  return [
    'my_template' =&gt; [
      'variables' =&gt; ['js_file_url' =&gt; NULL],
    ],
  ];
}


My output:

&lt;&gt;&lt;script src=http://google.com&gt;test&lt;/script&gt;&lt;/&gt;


Expected Output is 

&lt;script src=http://google.com&gt;test&lt;/script&gt;


How to get rid of empty tags =>  &lt;>, 

By default $attachments['#attached']['html_head'][] is adding the '#tag' even if i dont declare it.

Can someone help me, please.
You can attach custom tags to any render array from where it bubbles up into the HTML head. In the following sample I'm adding structured data when a certain block is viewed. $value then contains what's being printed between the opening and closing script tag.

/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function MYMODULE_block_view_system_breadcrumb_block_alter(array &amp;$build, BlockPluginInterface $block) {

  // Get JSON-LD.
  if ($json_ld = \Drupal::service('easy_breadcrumb.structured_data_json_ld')
    -&gt;value()) {

    // Prepare script tag.
    $structured_data = [
      '#tag' =&gt; 'script',
      '#attributes' =&gt; ['type' =&gt; 'application/ld+json'],
      '#value' =&gt; $json_ld,
    ];

    // Add script tag.
    $build['#attached']['html_head'][] = [
      $structured_data,
      'easy_breadcrumb_structured_data_json_ld',
    ];
  }
}


I hope you get the idea how this can easily be adjusted to get your custom snippet into the head. You can keep your logic in hook_page_attachments_alter but then let it look more like in the following snippet. Maybe you don't even need any #value at all.

/**
 * Implements hook_page_attachments_alter().
 */
function MYMODULE_page_attachments_alter(array &amp;$attachments) {

  if ($js_file_url = \Drupal::config('MYMODULE.settings')-&gt;get('url')) {

    // Prepare script tag.
    $my_script = [
      '#tag' =&gt; 'script',
      '#attributes' =&gt; ['src' =&gt; $js_file_url],
      '#value' =&gt; 'test',
    ];

    // Add script tag.
    $attachments['#attached']['html_head'][] = [
      $my_script,
      'MYMODULE_my_script',
    ];
  }
}