Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
coffee_page, tiny template functions in CoffeeScript
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;') = (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._ = ''
require './index'
page = html _,
head _,
title _,
text 'html'
color: 'red'
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

ghost commented Jan 4, 2013

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
  elem.b = b
  el = elem.b()
  delete elem.b


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment