具体实现的代码在 Github: https://gist.github.com/2498711 讨厌关闭括号关闭标签, 于是在用 Jade, 可浏览器端多少不方便 最后想起来以前一个办法, 给每个标签定义函数, 结合 coffee 的写法, 显得比较紧凑了
require './index'
page = html _,
head _,
title _,
text 'html'
style
body:
color: 'red'
div:
color: 'blue'
color2: 'bue'
color4: 'ue'
body _,
div id: 'main',
div id: 'left_bar',
nav id: 'home_button', class: 'nav'
nav id: 'search_button', class: 'nav'
nav id: 'msg_button', class: 'nav'
nav id: 'back_button', class: 'nav'
div id: 'right_bar',
article class: 'post',
p _,
text 'need to clarify sth'
text 'more things need to be examined'
article class: 'post'
article class: 'post'
article class: 'post'
console.log page
不知道会不会有潜在的问题, 请给看下....
现在计划用函数封装一下减少对全局变量的污染..
貌似直接封装, 函数的作用域链搞不定, 只能想到用面向对象的方法,
传一个函数, 进行一次赋值, 那么 this 就指向 tmpl 函数内部的对象了..
那样代码近似于:
tmpl ->
[@div](/user/div) {}, ([@text](/user/text) "content")
回复 (13)
尝试做了一下, 感觉有点怪, 不过个人还能接受 http://jiyinyiyong.github.com/lilyturf/page/ https://github.com/jiyinyiyong/lilyturf
多个属性呢,比如onclick之类的怎么写
多个属性就是 {} 多写键值对, 貌似没问题呀..
不多说了,看这个:https://github.com/gradus/coffeecup
例子里好象没有layout的用法
Layout? 不是 CSS 做的么? .. 我没写出来正规的模板引擎啊,, 可能理解有偏差
很早以前看 coffeecup 结果当时 -> 连用我还不懂 coffee 的语法能这么写...
没去想居然思路是一样的.. 居然有这种事情...
我的改进:dom.coffee 实现了 -> ,但是还是需要 @ ,coffeecup 怎么去掉 @ 依赖的还不知道,希望没有污染全局空间
原来你又改了... 我刚把 Coffeekup 那种办法想出来... 比较怀疑 Coffeekup 根本没处理过污染全局的问题, 因为人家就是模板引擎. 我是打算在 CoffeeScript 运行过程用, 所以才会考虑
log = console.log
elements = """
body head div section footer nav input p
"""
result = ""
stack = ""
html = (t) ->
stack = " " + stack
result += "\n#{stack}" + t
stack = stack[2..]
attrs = (options) ->
str = ""
for key, value of options
str += " #{key}='#{value}'"
str
elements.trim().split(/\s+/).map (tag) ->
global[tag] = (options, f...) ->
if (typeof options is "function")
f.unshift options
options = {}
result += "\n#{stack}<#{tag}#{attrs options}>"
stack = " " + stack
f.forEach (func) -> func()
stack = stack[2..]
result += "\n#{stack}</#{tag}>"
body class: "ok", ->
div class: "name", id: "fine", ->
p -> html "string"
p -> html "string"
p -> html "string"
log result
运行结果:
➤➤ coffee simulate.coffee
<body class='ok'>
<div class='name' id='fine'>
<p>
string
</p>
<p>
string
</p>
<p>
string
</p>
</div>
</body>
看了 coffeekup 代码, 人家用 eval 解决了全局变量的问题...
https://github.com/mauricemach/coffeekup/blob/master/src/coffeekup.coffee#L311-L324
对我来说难度比较大了, 貌似 eval 有些人不喜欢的
... 下意识写 eval 了,, 是 Function 生成函数..
找到了把函数的 template 转化到 string 的操作
https://github.com/mauricemach/coffeekup/blob/master/src/coffeekup.coffee#L280
表示函数生成器从来没用过.. 比不上 Lisp 来得简单,,
@logicthink 我只看到他用这个方案实现的, 但是细节也没看明白 ... 看懂了再说了