I've a drupal 8 website, where in every page, I would like to add a noscript tag for every script tag. In drupal 8, in html.html.twig, I saw the scripts variable in missing. So how do I do that in Drupal 8?
3 Answers
I wound up just putting the <noscript>
tag into my html.html.twig
template. There is a NoScript Tag module, but I didn't feel like adding a module to my site for this purpose.
You can do it in a custom module (MYMODULE.module):
use Drupal\Core\Render\Markup;
function MYMODULE_page_attachments(array &$page) {
$fallback = '<link href="fallback.css" rel="stylesheet" />';
$noscript = array(
'#tag' => 'noscript',
'#value' => Markup::create($fallback),
);
$page['#attached']['html_head'][] = [$noscript, 'mymodule'];
}
Depending where exactly you need the tag to be placed, there's also hook_page_top
and hook_page_bottom
to add markup either after the opening <body>
tag or right before the <footer>
tag (or wherever your theme has {{ page_top }}
and {{ page_bottom }}
placed exactly inside html.html.twig
).
Here's a sample that adds some marketing tool's <script>
and <noscript>
tags right after the opening <body>
tag.
/**
* Implements hook_page_top().
*/
function MYMODULE_page_top(array &$page_top) {
if (\Drupal::currentUser()->isAnonymous()) {
$foobar_script = [
'#type' => 'html_tag',
'#tag' => 'script',
'#attributes' => ['src' => 'https://example.com/js/example.js'],
];
$page_top['foobar_script'] = $foobar_script;
$foobar_noscript = [
'#type' => 'html_tag',
'#tag' => 'noscript',
'#value' => Markup::create('<img alt="" src="https://example.com/foobar.png" style="display:none;" />'),
];
$page_top['foobar_noscript'] = $foobar_noscript;
}
}