1

We have a custom theme, mytheme where we have the following library for the header-fix. I have also added {{ attach_library('mytheme/header-fix') }} to only one twig template block--myblock.html.twig that is for my custom block myblock.

The goal is to only add the library to myblock when myblock is rendered on the page.

The problem we are having is that the library is being added to all pages even ones where the block is not present (loaded on the page). How can we load a single library only on one block and not all the twig templates?

myblock configuration:

  1. restricted to only Article content type (so do not load on basic content type)

block--myblock.html.twig

{{ attach_library('mytheme/header-fix') }}
<div>
  <p>Continually fashion turnkey sources without web-enabled alignments. Some more content.</p>
</div>

mytheme.libraries.yml

...
header-fix:
  version: 1.x
  js:
    /path/to/header-fix.js: { preproces: false, attributes: { defer: true } }
...

mytheme.info.yml

...
libraries:
  - mytheme/header-fix
...
2

Just remove the reference from mytheme.info.yml.

That's adding it any time the theme is loaded (every page), whereas attach_library will add it only when that specific template is used.

You'll need to rebuild cache for the change to take effect.

| improve this answer | |

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.