CoffeeKup 将 CoffeeScript 转换为 HTML 代码
CoffeeKup 是一个基于 Node.js 和浏览器的模版引擎,你可以通过 CoffeeScript 编写 HTML 模版,然后通过 CoffeeKup 转变为真正的 HTML 代码。
特点
一种语言来统治他们。JavaScript 是无处不在的,因此是 CoffeeScript。服务器、浏览器甚至数据库。如果这个扩展呈现逻辑和 UI 结构(服务器和客户端)是理想的你,Coffeekup 是你的朋友。
更具体地说,一个优秀的语言。CoffeeScript 是一个地狱的一个干净的,富有表现力,灵活而强大的语言。很难找到这样的组合,特别是如果你需要它在浏览器中运行。
还没有另一种专门的语言来学习。可转让的知识型。
嵌入你的模板在CoffeeScript的好。模板是功能,所以他们不失去语法高亮和语法检查时,嵌入在CoffeeScript的应用。
在你的模板嵌入CoffeeScript的好。以同样的方式,你可以写在<script>
中 CoffeeScript块的内容,并保持突出。也许更重要的是,CoffeeScript 编译器不必称只是将这些块的JS,在其他模板引擎。
广泛的编辑支持。你从已经存在的列表中的优秀文本编辑器插件CoffeeScript的效益。
客户端服务器的一致性。在Node.js或浏览器相同的模板语言实现。
容易扩展到一个更高的水平“DSL”。因为所有的元素都只是功能,很容易定义你自己的自定义“标签”,这将工作和看起来一样的“本地”的。
HTML 5的准备。无聊的遗产doctypes和元素也可。
可选自动逃逸。你也可以用案例的基础上的辅助。
可选的格式,带线中断和缩进。
摘你的毒药。同时与CoffeeScript和JavaScript应用程序。
使用谨记
Coffeekup可 能不适用于这些情况下,你最好的选择:
- 你是最干净的语法可能后,上述所有。在这方面,一种特殊的语言,如 Jade 只是不能被击败。
- 你用 DIV 和/或Class的一切。而你能做的coffeekup div的# id.class。班级、专业语言常常有一个更短的语法。
- 你想绘制逻辑CoffeeScript,但你宁愿坚持使用HTML标记。然后你要寻找生态。
- 为您的特定项目/团队/喜好,你认为模板的有限的和/或独立的语言其实是有好处的。
安装
npm install coffeekup
获取 coffeekup
命令行,安装如下的代码:
npm install coffeekup -g
或者使用Git获取最新的版本
git clone git@github.com:mauricemach/coffeekup.git && cd coffeekup
cake build
npm link
cd ~/myproject
npm link coffeekup
使用方法
ck = require 'coffeekup'
ck.render -> h1 "You can feed me templates as functions."
ck.render "h1 'Or strings. I am not too picky.'"
定义一个变量
template = ->
h1 @title
form method: 'post', action: 'login', ->
textbox id: 'username'
textbox id: 'password'
button @title
helpers =
textbox: (attrs) ->
attrs.type = 'text'
attrs.name = attrs.id
input attrs
ck.render(template, title: 'Log In', hardcode: helpers)
预编译功能:
template = ck.compile(template, locals: yes, hardcode: {zig: 'zag'})
template(foo: 'bar', locals: {ping: 'pong'})
和 express 一起使用
app.set 'view engine', 'coffee'
app.register '.coffee', require('coffeekup').adapters.express
app.get '/', (req, res) ->
# Will render views/index.coffee:
res.render 'index', foo: 'bar'
和 zappa 一起使用
get '/': ->
@franks = ['miller', 'oz', 'sinatra', 'zappa']
render 'index'
view index: ->
for name in @franks
a href: "http://en.wikipedia.org/wiki/Frank_#{name}", -> name
和 meryl 一起使用
coffeekup = require 'coffeekup'
meryl.get '/', (req, resp) ->
people = ['bob', 'alice', 'meryl']
resp.render 'layout', content: 'index', context: {people: people}
meryl.run
templateExt: '.coffee'
templateFunc: coffeekup.adapters.meryl
在浏览器上面运行
<script src="template.js"></script>
<script>
$('body').append(templates.template({foo: 'bar'}));
</script>
这是一个多浏览器部署的可能性,预编译您的模板在服务器上的一个独立的功能。
命令行
$ coffeekup -h
Usage:
coffeekup [options] path/to/template.coffee
--js compile template to js function
-n, --namespace global object holding the templates (default: "templates")
-w, --watch watch templates for changes, and recompile
-o, --output set the directory for compiled html
-p, --print print the compiled html to stdout
-f, --format apply line breaks and indentation to html output
-u, --utils add helper locals (currently only "render")
-v, --version display CoffeeKup version
-h, --help display this help message
查看 /examples 完整版本(你必须先运行cake build
)。
请注意,即使所有的例子在CoffeeScript下运行,你也可以用纯JavaScript的环境运行测试。
The CoffeeKup object
Both the returned value from require 'coffeekup'
and the global CoffeeKup
created by <script src="coffeekup.js">
will have the following attributes:
compile
CoffeeKup.compile(template, options)
Compiles the template to a standalone function and returns it.
The input template can be provided as either a function or a string. In the latter case, the CoffeeScript compiler must be available.
Options:
locals
: if set to any "truthy" value, will compile the template with the main statements wrapped around awith
block. The template will then support thelocals
option (see below). This is the "runtime" method of putting external variables in the local scope of the template.hardcode
: an object containing values to be added to the template's local scope at "compile time". For each attribute in this object avar [name] = [stringified value]
will be added to the template body.
Compiled template
The compiled template returned will be a function accepting a single object parameter:
template(data)
All attributes in data
will be available to the template at @
(this
). Some attribute names are special and will trigger additional features:
locals
: if the template was compiled with thelocals
option, it will pass this variable to thewith
statement, putting all its attributes to the local scope.format
:false
by default. Whether to generate formatted HTML with indentation and line breaks, or just the natural "faux-minified" output.autoescape
:false
by default. Whether to autoescape all content or let you handle it on a case by case basis with theh
function.
render
CoffeeKup.render(template, data, options)
Compiles the template provided, runs it, and returns the resulting HTML string.
Options:
cache
:false
by default. Whether to reuse compiled templates, or re-compile them every time.
version
Version of CoffeeKup running.
doctypes
List of doctypes available to the doctype
function in templates. Object with doctype names as keys and their string contents as values. Can be customized at will.
The doctype named "default" will be used when none is specified (doctype()
).
tags
List of HTML elements available as functions. Array of strings, can be customized.
self_closing
List of self-closing tags. Array of strings, can be customized.
The template scope
CoffeeKup templates are CoffeeScript/JavaScript functions with certain special variables put in their local scope. These are usually functions, which will write their equivalent HTML to a buffer. The contents of this buffer will be the final return value of the template.
Tag functions
By far the most important of these functions are those equivalent to each HTML element. They'll write the tags and attributes necessary to render the element.
They're designed to look very similar to their HTML output when written in CoffeeScript.
Empty tags:
div()
<div></div>
img()
<img />
Attributes:
div str: 'str', num: 42, bool: yes, arr: [1, 2, 3], obj: {foo: 'bar', ping: 'pong'}
<div str="str" num="42" bool="bool" arr="1,2,3" obj-foo="bar" obj-ping="pong"><div>
div onclick: -> alert 'hi'
<div onclick="(function(){return alert('hi');}).call(this);"></div>
Contents (string):
h1 'foo'
<h1>Foo</h1>
h1 attr: 'value', 'foo'
<h1 attr="value">Foo</h1>
script '''
alert('foo');
console.log('bar');
'''
<script>alert('foo');
console.log('bar');</script>
Contents (function):
div -> 'Foo'
<div>Foo</div>
# equivalent to js: div(function(){'Foo'; return 'Bar';});
div ->
'Foo'
'Bar'
<div>
Bar
</div>
# equivalent to js: div(function(){'Foo'; div('Ping'); return 'Bar';});
div ->
'Foo'
div 'Ping'
'Bar'
<div>
<div>Ping</div>
Bar
</div>
# equivalent to js: div(function(){text('Foo'); div('Ping'); return 'Bar';});
div ->
text 'Foo'
div 'Ping'
'Bar'
<div>
Foo
<div>Ping</div>
Bar
</div>
ID/class shortcut
div '#id.class.anotherclass', 'string contents'
<div id="id" class="class anotherclass">string contents</div>
div '#id.class.anotherclass', -> h1 'Hullo'
<div id="id" class="class anotherclass"><h1>Hullo</h1></div>
div '#id.class.anotherclass', style: 'position: fixed', 'string contents'
<div id="id" class="class anotherclass" style="position: fixed">string contents</div>
Other locals
doctype
Writes the doctype. Usage: doctype()
(picks the default), doctype 'xml'
(specifying). You can see and modify the list of doctypes at CoffeeKup.doctypes
.
comment
Writes an HTML comment.
ie
Writes an IE conditional comment. Ex.:
ie 'gte IE8', ->
link href: 'ie.css', rel: 'stylesheet'
<!--[if gte IE8]>
<link href="ie.css" rel="stylesheet" />
<![endif]-->
text
Writes arbitrary text to the buffer.
tag
Used for arbitrary tags. Works like the builtin tags, but the first string parameter is the name of the tag.
coffeescript
CoffeeScript-friendly shortcut to script
:
coffeescript -> alert 'hi'
<script>
[COFFEESCRIPT_HELPERS]
(function(){return alert('hi');}).call(this);
</script>
coffeescript "alert 'hi'"
<script type="text/coffeescript">alert 'hi'</script>
coffeescript src: 'script.coffee'
<script type="text/coffeescript" src="script.coffee"></script>
yield
Returns the output of a template chunk as a string instead of writing it to the buffer. Useful for string interpolations. Ex.:
p "This text could use #{yield -> a href: '/', 'a link'}."
<p>This text could use <a href="/">a link</a>.</p>
Without it, the a
function runs first, writes to the buffer and returns null
, resulting in a useless output:
p "This text could use #{a href: '/', 'a link'}."
<a href="/">a link</a><p>This text could use null.</p>
@
CoffeeScript shortcut to this
. This is where all the input data can be accessed.
Extending CoffeeKup
template = ->
h1 @title
form method: 'post', action: 'login', ->
textbox id: 'username'
textbox id: 'password'
button @title
helpers =
textbox: (attrs) ->
attrs.type = 'text'
attrs.name = attrs.id
input attrs
console.log CoffeeKup.render template, title: 'Log In', hardcode: helpers
相关链接
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论