how to use html templates in CouchDB

commonjs, couchdb, kanso, templates, underscore.js

Solution

I'm unfamiliar with Kanso, but before CouchDB 1.1, view/show etc. functions in CouchDB could not include anything. (The CouchApp tool had its own `!include` workarounds to solve this.) These are not necessary anymore. CouchDB 1.1 added CommonJS support.

Tll the templates and libraries must be part of the design document. You can access the raw values (as a string) by referencing `this.some_key`; or load them via CommonJS by executing `require("some_key")`.

For example:

exports.example_view = {
    map: function (doc) {
        // this must be placed *inside* the map function
        var example = require('views/lib/example');
        if (doc.num) {
            emit(doc._id, example.fn());
        }
    }
};

(Sharing code between views)

To render templates server-side, you'll need to encode them as string and require them like you require other JavaScript libraries. (For browser-side rendering, fetching attachments via AJAX works.)

Problem

I've been searching everywhere trying to figure this one out. I'm trying to generate html pages from couchdb show and list functions. I'd like to leverage underscore.js's template solution. The part I'm getting stuck on is how to include html templates in my show and list functions. Where do I store them? As attachments? And then how do I reference them in my show and list functions. I assume !json and !code macros are not being used, and I can't figure out how to use require() from common js to do it. Any help would rock! Thanks! Extra Info: I'm using Kanso to push my apps, not CouchApp.

Original source

Related problems