0

I have a custom block with its own twig template file.

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.

3

See NodeViewController::view():

  $build['#attached']['html_head_link'][] = array(
    array(
      'rel' => $rel,
      'href' => $node->url($rel),
    ),
    TRUE,
  );

You can add html_head_link #attached elements anywhere, including in your block, and it will bubble up and be added to any page that shows your block.

0

Thanks Berdir,

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 calling the above function conditionally in mytheme_preprocess_block(&variables) by checking $variables['attributes']['id']

  • Just put it in the render array returned by the block, don't do it in preprocess. – Berdir Nov 20 '15 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.