public
Last active

coffee_page, tiny template functions in CoffeeScript

  • Download Gist
index.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
 
pair_elems = 'html head title body script '
pair_elems+= 'div nav header footer section article '
pair_elems+= 'p span textarea br pre code '
pair_elems+= 'ul li ol table tr td'
pair_elems = pair_elems.split ' '
 
single_elems = 'img meta input link'
single_elems = single_elems.split ' '
 
write = (attrs) ->
attr_str = ''
if typeof attrs is 'object'
for key, value of attrs
attr_str+= " #{key}=\"#{value}\""
return attr_str
 
for elem in pair_elems
do (elem) ->
global[elem] = (attrs, elems...) ->
"<#{elem}#{write attrs}>#{elems.join ''}</#{elem}>"
 
for elem in single_elems
do (elem) -> global[elem] = (attrs) -> "<#{elem}#{write attrs}/>"
 
global.text = (str) -> str.replace(/\s/g, '&nbsp')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
 
global.style = (attrs) ->
str = ''
for key, value of attrs
st = ''
for k, v of value
while (k.match /\d$/)?
k = k[...-1]
st+= "#{k}: #{v};"
str += "#{key}{#{st}}"
return "<style>#{str}</style>"
 
global.hsla = (h, s, l, a) -> "hsla(#{h},#{s}%,#{l}%,#{a/100})"
global._ = ''
test.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 
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
newElem = (s) ->
  document.createElement s
newText = (s) ->
  document.createTextNode s

tagNames = "head title body script nav 
div header footer section article 
p span textarea br pre code a address b backquote 
button font frame form hr i 
ul li ol table tr td th title 
canvas audio video select style img 
meta input link iframe audio video".split /\s+/

elem = (b) ->
  tagNames.forEach (s) ->
    elem[s] = (obj, children...) ->
      el = newElem s
      if children.length == 0
        children[0] = obj
        obj = {}
      for k, v of obj
        el.setAttribute k, v
      children.forEach (c) ->
        if typeof(c) == "string"
          c = newText c
        el.appendChild c
      el
  elem.b = b
  el = elem.b()
  delete elem.b
  el

不再需要{}和text

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.