I have a custom block with its twig template suggestion.

I want to add an html head link tag when this block is loaded.
ex: <link rel="import" href="test.html">

In the twig template I can use attach_library to add css/js to , but I don't know how to add html imports in twig.

Is it possible to achieve this using mytheme_preprocess_block function, or any other hook?

I can add the html head link tag in mytheme_page_attachments_alter but I don't know how to limit this to only when my custom block is loaded.

Thank you.

Comments

ahwebd’s picture

What I was missing is using \Drupal::service('renderer')->render()

I created an array with #attached key, then rendered it using the above method.

// Attach html head link.
function mytheme_attach_html_head_link($href) {
  // Prepare html head link tag.
  $link = array( array(
    'rel' => 'import',
    'href' => $href,
  ));
  // Attach link tag.
  $element = array();
  $element['#attached']['html_head_link'][] = $link;
  \Drupal::service('renderer')->render($element);
}

Then I was the calling the above function conditionally in mytheme_preprocess_block(&variables) by checking $variables['attributes']['id']