用于python的handlebars.js模板。
pybars的Python项目详细描述
Copyright (c) 2012, Canonical Ltd
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 only.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. GNU Lesser General Public License version 3 (see the file LICENSE).
pybar为python提供了一个与 把手.js.
依赖关系
- Python2.6+
- pymeta(https://launchpad.net/pymeta)
测试依赖项
用法
有关模板语言的详细信息,请参见http://handlebarsjs.com/ 文档。
将引擎转换为python需要稍微不同的调用 js版本的约定:
- 块助手获取(this,options,*args,**kwargs)
- 其他助手获取(this,*args,**kwargs)
- 上下文中的闭包take(this,*args,**kwargs)
像{foo bar qux=1}}这样的模板将bar作为位置参数传递,并且 Quux作为关键字参数。关键字参数必须是中的非保留字 Python。例如,“print”作为关键字参数将失败。
具有文本布尔参数(如{{foo true})的模板将具有 根据需要映射到python的true或false的参数。
为了提高效率,pybar传递的不是字符串,而是 list('liststr'),它有一个返回 加入(自我)。模板帮助程序可以返回列表、元组、Unicode或 liststr实例。避免字符串中的二次开销。 模板呈现期间的处理。处于内部循环中的帮助程序应该 出于同样的原因返回list或liststr。
注意liststr在js实现中占据safestring的位置: 当返回liststr时,它将不会被转义,即使在常规的{{} 扩张。
js实现中的“data”工具在此未被移植 重点是,如果有需求的话,很容易补充。类似地 stringparams特性没有被移植-引用任何您想要强制的内容 到helper调用中的字符串。
典型用法:
获取编译器:
>>> from pybars import Compiler >>> compiler = Compiler()
注册任何需要的扩展名:
>>> def _list(this, options, items): ... result = [u'<ul>'] ... for thing in items: ... result.append(u'<li>') ... result.extend(options['fn'](thing)) ... result.append(u'</li>') ... result.append(u'</ul>') ... return result >>> compiler.register_helper(u'list', _list)
并编译模板:
>>> source = u"{{#list people}}{{firstName}} {{lastName}}{{/list}}" >>> template = compiler.compile(source)
现在可以渲染它:
>>> template({ ... 'people': [ ... {'firstName': "Yehuda", 'lastName': "Katz"}, ... {'firstName': "Carl", 'lastName': "Lerche"}, ... {'firstName': "Alan", 'lastName': "Johnson"} ... ]}) <ul><li>Yehuda Katz</li><li>Carl Lerche</li><li>Alan Johnson</li></ul>
更多细节可以通过阅读api文档(例如pydoc pybar)找到。
安装
在具有所有可用依赖项的环境中运行setup.py,或者 将工作目录添加到pythonpath。
开发
上游开发发生在https://launchpad.net/pybars。 如果依赖项不是 立即可用,您可以使用./bootstrap.py创建bin/buildout,然后 bin/py以获得具有可用依赖项的python解释器。
要使用您选择的运行程序运行测试,测试套件是 Pybars.tests.test_套件。
例如:
$ bin/py -m testtools.run pybars.tests.test_suite
Pybars启用了TestRepository,因此您只需执行以下操作:
$ testr init $ testr run