Theming Drupal 8: How To Include the Facebook JavaScript SDK

That time have come - and I have started to officially develop my first Drupal 8 site - I won't go into details by comparing Drupal 8 vs Drupal 7 or Drupal 6 (as I think that's a topic for another article).

Today I will show how one (perhaps you) can include default Facebook JavaScript SDK library to your Drupal 8 site. I'm working on simple business website, which has a Facebook business page, and we want to include Facebook page plugin into site's sidebar.

For getting actual code, you must first visit Developers Central on Facebook and customize your Page plugin according to your need, next you must copy/paste two sections of code. First - include SDK library, second paste actual code to generate Facebook page plugin on your Drupal site.

Include the JavaScript SDK on your page once, ideally right after the opening <body> tag.

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.8&appId=YOUR_ID";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

For pasting code into sidebar I'm going to use Drupal blocks section, but to actually get them working we must include JavaScript SDK library into theme. The principles for including library into Drupal 8are more or less the same as it is in Drupal 7.

Place this code wherever you want the plugin to appear on your page.

<div class="fb-page" data-href="https://www.facebook.com/yourpage/" data-tabs="timeline" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><blockquote cite="https://www.facebook.com/yourpage/" class="fb-xfbml-parse-ignore"><a href="https://www.facebook.com/yourpage/">yourpage</a></blockquote></div>

For this project I'm using a free Drupal Zymphonies theme. Thus the basics applies to every Drupal 8 theme. 

Locate the html.htnl.twig file (for Zymphonies theme - theme/drupal8_zymphonies_theme/templates/layout)

Copy code you get at developers.facebook.com, save file, right after the opening <body> tag, clear cache and you are done.

Hope this helps!