如何在CouchDB中使用html模板

时间:2012-04-06 05:43:45

标签: templates couchdb underscore.js commonjs kanso

我一直在寻找各种各样的想法。我正在尝试从couchdb show和list函数生成html页面。我想利用underscore.js的模板解决方案。我要坚持的部分是如何在我的节目和列表函数中包含html模板。

我在哪里存放它们?作为附件?然后我如何在我的节目和列表功能中引用它们。我假设!json和!代码宏没有被使用,我无法弄清楚如何使用常见的js中的require()来实现它。

任何帮助都会摇滚!

谢谢!

额外信息:我正在使用Kanso推送我的应用,而不是CouchApp。

2 个答案:

答案 0 :(得分:5)

根据定义,CouchDB附件是not accessible in show and list functions

显示和列出功能支持CommonJS。因此,您只需在设计文档中包含任何库。

{ "_id": "_design/example"
, "say_hi": "module.exports = function(person) { return 'Hello, ' + person }"
, "shows":
  { "hello": "function(doc, req) { var hi = require('say_hi'); return hi(req.query.me) }"
  }
}

此视图将如下所示

GET /my_db/_design/example/_show/hello?me=Jason

HTTP/1.1 200 OK
Server: CouchDB/1.2.0 (Erlang OTP/R15B)
Date: Fri, 06 Apr 2012 11:02:33 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 12


Hello, Jason

答案 1 :(得分:4)

我对Kanso不熟悉,但在CouchDB 1.1之前,CouchDB中的查看/显示等功能无法包含任何内容。 (CouchApp工具有自己的!include解决方法来解决这个问题。)这些不再是必需的了。 CouchDB 1.1增加了CommonJS支持。

模板和库必须是设计文档的一部分。您可以通过引用this.some_key来访问原始值(作为字符串);或者通过执行require("some_key")来通过CommonJS加载它们。

例如:

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

要在服务器端呈现模板,您需要将它们编码为字符串,并且需要它们,就像您需要其他JavaScript库一样。 (对于浏览器端渲染,通过AJAX获取附件有效。)