What would be the best way to add code inside the tag of specific content type?

Display Suite is being used for layout and we are using a custom theme. Have created html.html.twig. If I add anything to the head tags of this file, of course, it shows on all the pages.

Can we create a separate template such as html--content-type.html.twig then add the code there?

If not what would be the Drupal way of adding this code to the head tags for only specific content type?

<script async 
     (adsbygoogle = window.adsbygoogle || []).push({
          google_ad_client: "ca-pub-3********",
          enable_page_level_ads: true

The quick way

and maybe some will call it dirty way would be to add in your THEMENAME.theme file

function THEMENAME_preprocess_html(&$vars) {  
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    // You can get nid and anything else you need from the node object.
    $vars["content_type"] = $node->bundle();

and then in your html.html.twig

{% if content_type == "page" %}
  <script> ... </script>
{% endif %}      


you can just put it in a .js file and include like this

function my_module_preprocess_html(&$variables) {
  // To get around the issue of D8 core escaping inline js we cram our js
  // file into a twig variable for printing "raw" in "html.html.twig" like so: 
  // {{ my_module_script|raw }}
  $variables['my_module_script'] = '<script type="text/javascript">' . file_get_contents(dirname(__FILE__) . '/js/script.js') . '</script>';

as described in this comment

proper way is probably to

Define a library and then to attach it following this guide

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.