0

I wonder how to attach a library to a specific block. I do this:

in mytheme.libraries.yml

   lib-name-script:
      js:
        header: true
        js/masonry.pkgd.min.js: {}
        js/main.js: {}
      dependencies:
        - core/jquery

in main.js

jQuery(document).ready(function() {

    $('.grid').masonry({
        itemSelector: '.grid-item',
        columnWidth: 220,
        horizontalOrder: true
    });
});

and in views-view--block-some.html.twig

{{ attach_library('theme_name/lib-name-script') }}

<div class="grid">
    {{ rows }}
</div>

But from some reason this dont works. :S

On the and of file I have:

<script src="/themes/theme_name/js/masonry.pkgd.min.js?oxcmsf"></script>
<script src="/themes/theme_name/js/main.js?oxcmsf"></script>

Was I corect load js, or mistake is on some other place?

1
1

It sure looks like you are on the right track to me. I've used the same approach myself. See: https://github.com/vegantriathlete/presentation/blob/master/templates/node--slide--full.html.twig

Have you cleared the cache? Maybe the theme registry needs to be updated to reflect the template you are using.

Have you viewed the page source of the page when that block is visible to see if the javascript is being included? Maybe the javascript is being attached and you've got a bug in your main.js. You aren't following the pattern of how to attach javascript. see: https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

6
  • 1
    Ah, it seems you edited your question as I was writing this answer. If I am reading your edit correctly, it does appear that the javascript is being loaded on the page. So, I'd suspect that maybe it has to do with not following the correct pattern of how to attach javascript. – vegantriathlete Oct 5 '17 at 12:09
  • 1
    In addition to the link I've given to the Drupal 8 docs you can have a look at github.com/vegantriathlete/presentation/blob/master/js/slide.js to see how I've done it. – vegantriathlete Oct 5 '17 at 12:10
  • Its look like the problem is on main.js and I didnt use corect pattern of how to attach javascript. To be honest this code make me confuse. prntscr.com/gtktvr – SakaSerbia Oct 5 '17 at 12:11
  • 1
    Have a look at the two links I provided on using the correct pattern to attach javascript (one of which is the page you are sharing in your screen shot). – vegantriathlete Oct 5 '17 at 12:14
  • Yes, the problem was in main.js. I solve problem. Thank you a lot for help. – SakaSerbia Oct 5 '17 at 12:18
0

The problem was in main.js This solve my problem. Thank you vegantriathlete for help.

(function ($) {

    $('.grid').masonry({
        itemSelector: '.grid-item',
        columnWidth: 220,
        horizontalOrder: true
    });

})(jQuery);

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.