Carpe diem (Felix's blog)

I am a happy developer

Jekyll/Octopress Hacker News Plugin

Inspiration

I found out that some cool blogs have a cute hacker news like button on each of its posts.

The service is HN Like Button, created by shashyal. To use it you can use the generator like so:

However, we don’t want to do that every time, right? So I decided to write a small Jekyll plugin to generate the button automatically. Hope you can enjoy it!

The hidden API of HNLike

Well…not really. The generated html snippet looks like this:

1
2
3
<iframe frameborder="no" scrolling="no" height="50px" width="350px"
 src="http://hnlike.com/upvote.php?link=http%3A%2F%2Fdryman.github.com%2Fblog%2F2012%2F04%2F04%2Fjekyll-graphviz-plugin%2F&title=Jekyll%20Graphviz%20Plugin"
 >iframes not supported by your browser</iframe>

Observe that in the src after the upvote.php? there are only two key valure pairs:

  1. link=html link
  2. &title=title text

We just need to replace the html link and title text to our URL-escaped string and it is done.

Integrate with Jekyll

Jekyll/Octopress is designed to extend its functionality by users. For details you can take a look at Theming and Customization - Octopress. Follow the instructions, I simply added a new html snippet in source/_includes/.

hn_like.html link
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{% if site.hn_like_button %}
  <script type="text/javascript">
    (function(){
      var hn_like = document.createElement('iframe');
      hn_like.frameborder="no";
      hn_like.scrolling="no";
      hn_like.height="28px";
      hn_like.width="115px";
      hn_like.src = "http://hnlike.com/upvote.php?link="
                    + encodeURIComponent(document.location)
                    + "&title="
                    + encodeURIComponent("{{ page.title }}");
      hn_like.innerHTML="iframes not supported by your browser";
      var twitter = document.getElementsByClassName("twitter-share-button")[0];

      twitter.parentNode.insertBefore(
        hn_like,
        twitter
      );
    })();
  </script>
{% endif %}

I modified the height and width otherwise it will be too big. Also I use jekyll liquid helpers instead of document.title to form title text. Finally I use the twitter-share-button element to position where I should insert the button in.

Installation steps

  1. To extend the built in snippet, download hn_like.html into your source/_includes directory

  2. Add one line {% include hn_like.html %} into source/_includes/after_footer.html.

  3. Add

1
2
# hacker news like button
hn_like_button: true

into your _config.yml.

Edit:

The vote won’t update immediately. It will show up until hacker news index the post and can be reached via HN search API.

Edit: 2012-04-07

I changed my domain name and all HN/Twitter/FB/G+ counts reset to zero. So I submit the post to HN again.

Comments