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