1

I created a custom Theme: filhos_do_porto using Bartik as a subtheme and I would like to add JS code only to the Front Page.

Can someone help me? (I didn’t find anything specific of D8 clear enough for someone new in Drupal)

4

One way, in your mytheme.theme file:

/**
 * Implements hook_page_attachments_alter().
 */
function mytheme_page_attachments_alter(&$attachments) {
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $attachments['#attached']['library'][] = 'mytheme/library-name';
  }
}

This points to an entry in your mytheme.libraries.yml file which list out what file(s) to load.

|improve this answer|||||
  • Thanks for your prompt reply. Sorry for my ignorance but I can not make it work. A added to my filhos_do_porto.libraries.yml file the text: front-library: js: js/onlyfront.js: {} And added to my filhos_do_porto.theme file the text: <?php function mytheme_page_attachments_alter(&$attachments) { if (\Drupal::service('path.matcher')->isFrontPage()) { $attachments['#attached']['library'][] = 'filhos_do_porto/front-library'; } } But it’s not working, what am I doing wrong? – Henrique Moreira Apr 19 '18 at 17:44
  • You dont literally use mytheme ... mytheme should be replaced with the machine name of your theme. filhos_do_porto – Kevin Apr 19 '18 at 17:55
  • mytheme or mymodule is just a naming convention people use on here and elsewhere – Kevin Apr 19 '18 at 18:11

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.