Creating a Twitter Share block programmatically in Drupal 8

Creating a Twitter Share block programmatically in Drupal 8

On14th Mar 2017, 2024-12-02T21:27:45+05:30 ByKarthik Kumar D K | read
Listen Pause Resume Stop

How to Create a Twitter Share block programmatically in Drupal 8. Which includes few minor stuff like

  • Accessing the Current Node data in Block.
  • How do we create the link programmatically.
  • Disable cache for particular block.
  public function build() {    $node = \Drupal::request()->attributes->get('node');    $options = array(      'query' => array(        'text' => t($node->getTitle()),        'hashtags' => t('drupal'),        'via' => t('heykarthikwithu'),      ),      'attributes' => array(        'target' => '_blank',        'class' => 'twitter-share'      ),    );    $url = Url::fromUri('https://twitter.com/share', $options);    $link = Link::fromTextAndUrl('Share it on Twitter..?', $url);    $build['#markup'] = $link->toString();    $build['#cache']['max-age'] = 0;    return $build;  }

Well this was the piece of code which is written in this site to share content in Twitter..

1. Accessing the Current Node data in Block

$node = \Drupal::request()->attributes->get('node');

2. To Create the link programmatically

    $options = array(      'query' => array(        'text' => t($node->getTitle()),        'hashtags' => t('drupal'),        'via' => t('heykarthikwithu'),      ),      'attributes' => array(        'target' => '_blank',        'class' => 'twitter-share'      ),    );    $url = Url::fromUri('https://twitter.com/share', $options);    $link = Link::fromTextAndUrl('Share it on Twitter..?', $url);    $build['#markup'] = $link->toString();

3. To disable cache for particular block

$build['#cache']['max-age'] = 0;

Thank you :)

Related Articles

Recent Articles

Recent Quick Read

Recent Great People

We Need Your Consent
By clicking “Accept Cookies”, you agree to the storing of cookies on your device to enhance your site navigation experience.
I Accept Cookies