Add a Twitter card

Let's add a Twitter card. A Twitter card is a function that allows you to post a summary on Twitter simply by linking to an article.

Open build script

First of all, open the Perl script that is building your site.

lib / Giblog / Command / build.pm

Added a program to add a Twitter card

Add a Perl program for "Twitter card" between "Add meta description" and "Build entry html".

    #Add meta description
    $api->add_meta_description($data);
    
    #Twitter card
    {
      my $meta = $data->{meta};
      
      my $site_url = $config->{site_url};
      my $title = $data->{title} ||'';
      my $description = $data->{description} ||'';
      
      my $twitter_card = << "EOS";
<meta name = "twitter: card" content = "summary" />
<meta name = "twitter: site" content = "\ @perlzemi" />
<meta name = "twitter: title" content = "$title" />
<meta name = "twitter: description" content = "$description" />
<meta name = "twitter: image" content = "$site_url /images/perlzemi-twitter-card.png" />
EOS
      
      $meta. = "\ n $twitter_card\n";
      
      $data->{meta} = $meta;
    }
    
    #Build entry html
    $api->build_entry($data);

This way you can write Perl programs directly to customize your site.

How to check your Twitter card

To check if the Twitter card is displayed correctly, use the "Card validator" provided by Twitter.

Card validator

How to display the first image of an article?

On smartphone sites, it's also common to put the first image of an article on a Twitter Card.

If you want to see the first image of an article, do the following:

Add a Perl program to get the first image between "Create description from first p tag" and "Read common templates".

    #Create description from first p tag
    $api->parse_description_from_first_p_tag($data);

    #Get first image src
    $api->parse_first_img_src($data);

    #Read common templates
    $api->read_common_templates($data);

Next, describe the part of the Twitter card as follows.

    #Add meta description
    $api->add_meta_description($data);
    
    #Twitter card
    {
      my $meta = $data->{meta};
      
      my $site_url = $config->{site_url};
      my $title = $data->{title} ||'';
      my $description = $data->{description} ||'';
      my $img_src = $data->{img_src};
      
      my $twitter_card = << "EOS";
<meta name = "twitter: card" content = "summary" />
<meta name = "twitter: site" content = "\ @perlzemi" />
<meta name = "twitter: title" content = "$title" />
<meta name = "twitter: description" content = "$description" />
EOS
      if (defined $img_src) {
        $twitter_card. = << "EOS";
<meta name = "twitter: image" content = "$site_url $img_src" />
EOS
      }
      
      $meta. = "\ n $twitter_card\n";
      
      $data->{meta} = $meta;
    }
    
    #Build entry html
    $api->build_entry($data);