How to add inline JS script to a page or block programmatically to drupal 8/9 ?
Method 1 : Form hook_page_attachments
Example:
/**
* Implements hook_page_attachments().
*/
function MYMODULE_page_attachments(array &$attachments) {
// You can optionally perform a check to make sure you target a specific page.
if (\Drupal::routeMatch()->getRouteName() == 'some.route') {
// Add our JS.
$attachments['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#attributes' => [
'type' => 'text/javascript',
],
'#value' => \Drupal\Core\Render\Markup::create('console.log("i am here");'),
], 'key_for_this_snippet',
];
}
}
Method 2 : Form a controller (Or other renderer array)
Example:
/**
* Test page
*/
public function aPage() {
$output = [];
// Your page
$output['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#attributes' => [
'type' => 'text/javascript',
],
'#value' => \Drupal\Core\Render\Markup::create('console.log("i am here");'),
], 'key_for_this_snippet',
];
return $output;
}
Comments