Drupal 8- adding header tags in html.twig file based on content type

There will be situation where  you want to show some meta tags or any other header tag  in front  page and some other tags in inner pages of content types. Here I am explaining how we can show meta tags based on  content types. As you know if you search term  adding metag  in Drupal8 you will get YOUR_THEME _page_attachments_alter hook function.

You can use these hook function to append meta tags  to html header and that will be applicable to all pages. But suppose you want to show  meta tag only in inner page of an content. We will try to write an condition in page_attachments_alter function . it will looks like below

Now you want to write some conditions in above hook function. First We will try to get view id of page view

But here $view_id v=will be empty.
Also if you print $page variable , you can see only attachement details like all header tags currently available. There is no way to identify which content type page rendering. So we will achieve conditional meta tag appending in different way.

First we will go to preprocess_html() function in .theme file. here you can print $variables array. So if you are in a content type inner page you can see node_type key in this array. node_type value represents which content type is loading now. if you are loading a front page node_type key wont be there in $variables array.
Please see below code snippent in .theme files where you can see variable values.

Next we are going to create condition where we will check whether node_type is present there or not . if a particular node type is present we will create another variable that will be accessed from html.twig file

Now we are going to html.twig file and access is_content_page value . based on this value we can show meta tags in twig.

Here you can see based on if condition you can show any types of header tags in html.twig file.
flush the cache and open front page and content type view page. If you check source of page you can identify the difference.

Here I explained how we can show meta tags in different pages based on if conditions. The same logic we can use to show and hide different header tags in each views and pages.

Downlod Free Ebook on Drupal theme tutorial

Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )
if you like this article Buy Me A Coffee this will be an ispiration for me to write articles like this.

You may also like...