Monday, June 30, 2014

QR Codes in Handlebars

User’s don’t like to type in long URLs, and if they are on mobile they don’t like to type at all. Here is a simple Handlebars helper to make QR codes. But first, here is how easy it is to use:
  {{{qrcode ""}}}
Why would you want a QR code in a web site, when you could just as well put a clickable link? One example is to move a URL from viewing it on a desktop to your mobile. Another example is for ticketing: you put a booking code in the URL, make a QR code from it, and the venue will scan it (and the URL takes them directly to the validation function of their web app). No typing. Quick, safe and easy for everyone involved.
Handlebars is a JavaScript templating engine, easy to use and understand, and it allows expanding it with your own plugins, which thankfully are equally easy to write. Here is the above plugin, in full:
Handlebars.registerHelper("qrcode", function(data) {
var qrcode  = new QRCode(-1,QRErrorCorrectLevel.H);

var bg="#fff",fg="#000";
var n=qrcode.getModuleCount();
var tilesize = 4;
var sz=n*tilesize;

var s='<table style="width:'+sz+'px;height:'+sz+
for(var row = 0; row < n; row++ ){
    s+='<tr style="height:'+tilesize+'px">';
    for(var col = 0; col < n; col++ ){
        s+='<td style="background:'+
          (qrcode.isDark(row, col) ? fg:bg)+
return s;
To use this plugin you need to fetch an open-source JavaScript library unzip it and include it on your site with:
<script type="text/javascript" src="qrcode.min.js">
Aside: the core of the above plugin was taken from one of the examples that come with the library. I chose to use tables, rather than canvas, as it gives much wider browser support, with no disadvantage.
Written with StackEdit.

No comments: