Creating a Twitter Share block programmatically in Drupal 8

ByKarthik Kumar D Kon14th Mar 2017, 2022-12-01T08:00:00+05:30
Read Article
Pause
Resume
Stop
Creating a Twitter Share block programmatically in Drupal 8

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 :)

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