Wednesday, 12 June 2013

JQTPL old "tmpl" method is now "render"

To anybody who uses JQTPL already this will be obvious, but I just thought I'd post this for anybody who might have gone down the path I did.

As I mentioned in this post on Stack Overflow I'd been trying to get node.js set up (on my Mac) per Adam Freeman's Apress Book "Pro JavaScript for Web Apps".  The issue I was facing is that it seemed the API changed for JQTPL such that there is no longer a "tmpl" method as implied by this, and also as is clear from reading the source code of jqtpl.js (the current version of which only appears to have "render", "compile", "cache" and "$" methods as per this page.

Adam's code from his "server.js" file contains the following line:

    res.write(jqtpl.tmpl(loadTemplate(req.url.substring(1)), data));

which causes the following error:

    /Users/dave/NodeJsTesting/server.js:43
                            res.write(jqtpl.tmpl(loadTemplate(req.url.substrin
                ^
    TypeError: Object # has no method 'tmpl'
        at IncomingMessage. (/Users/dave/NodeJsTesting/server.js:43:45)
        at IncomingMessage.EventEmitter.emit (events.js:92:17)
        at _stream_readable.js:910:16
        at process._tickCallback (node.js:415:13)

It turns out (if you're using a more recent version of JQTPL like I was) you just have to change "tmpl" to "render" in Adam's "server.js" file.

cheers
Dave



2 comments:

  1. I am working on this book now. Did you finish? Mind if I hit you up if I get stuck (I doubt I will, but always good to know :)

    ReplyDelete
  2. For instance I had to refactor server.js a little as the totals were wrong. It appears that jqtpl makes a few calls on the methods to determine what the returns are so it knows how to display them. As such, it was calling the method to get the subtotal for an item in the basket 4 times and that method adds to the total each time (causing the total to be 4 times larger than it should be). Here is my refactor:

    subtotals: {},
    getTotal: function() {
    var runningTotal = 0;
    for (var id in this.subtotals) {
    runningTotal += +this.subtotals[id];
    }
    return runningTotal;
    },
    getSubtotal: function(id, quantity) {
    var price = this.getProp(id, "price") * quantity;
    if (! (id in this.subtotals)) {
    this.subtotals[id] = price;
    }
    return price;
    }

    ReplyDelete