Twitter Mention to Url Convertor Plugin for Octopress

| Comments

Today i needed to convert a string like "Hello world @quentinrousseau" to an html string like with the Twitter mention decoded with a real link for Octopress.

There is a gem called twitter_text who is already doing this stuff available here : https://github.com/twitter/twitter-text-rb.

But it was too overkilled for my decoding in my case only the mention.

So i developped this little plugin for Octopress who is doing the stuff well and simple.

Gist available here : https://gist.github.com/kwent/8295854

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Title: Twitter mention to url convertor plugin for Octopress
# Author: Quentin Rousseau http://quentinrousseau.com
# Description: Convert all twitter mentions with an url.
#
# Syntax 
#
# Example:
# 
#
# Output:
# <a href="https://twitter.com/quentinrousseau" alt="@quentinrousseau">@quentinrousseau</a>
#

module Jekyll

  class TwitterMentionConvertor < Liquid::Tag

    @twitter_base_uri = nil

    def initialize(tag_name, markup, tokens)
      super
      @twitter_base_uri = "https://twitter.com/"
    end

    def render(context)
      "#{context[@markup.strip]}".gsub(/@([a-z0-9_]+)/i) do |mention|
        "<a href=\"#{@twitter_base_uri}#{mention[1..-1]}\" alt=\"#{mention}\">#{mention}</a>"
      end
    end

  end

end

Liquid::Template.register_tag('twitter_mention_convertor', Jekyll::TwitterMentionConvertor)

Enjoy !

More…