How to add direct share links to your Drupal page in page.html.twig

The following snippets can be used to get direct share links to Facebook, Twitter and LinkedIn in your page.html.twig. 

First, to your mytheme.theme, add

/**
 * Implements hook_preprocess_page().
 */
function mytheme_preprocess_page(&$variables) {
 if(isset($variables['node'])) {
    $variables['page_title'] = $variables['node']->title->value;
  }
  else{
    $variables['page_title'] =$variables['page']['#title'];
  }
}

Then, in page.html.twig:

<a href="https://www.facebook.com/sharer.php?u={{ url('<current>') }}" class="btn-facebook">
  Share on Facebook
</a>
<a href="https://twitter.com/share?url={{ url('<current>') }}&text={{ page_title }}" class="btn-twitter">
  Share on Twitter
</a>
<a href="https://www.linkedin.com/shareArticle?url={{ url('<current>') }}&title={{ page_title }}" class="btn-linkedin">
  Share on LinkedIn
</a>

 

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!