Skip to content

Instantly share code, notes, and snippets.

@comfuture
Created December 7, 2011 09:49
Show Gist options
  • Save comfuture/1442208 to your computer and use it in GitHub Desktop.
Save comfuture/1442208 to your computer and use it in GitHub Desktop.
proposal of javascript like template syntax

Overview

  • 각 html엘리먼트명에 대응하는 함수는 String, Array, Object의 3가지 형태의 파라메터를 받을 수 있다. 모든 파라메터를 생략 가능하고 순서는 상관 없다.
    • String형은 innerHTML에 대응
    • Object형은 attributes에 대응
    • Array형은 child elements에 대응, Array의 요소로써 String은 textNode에 대응

Templating

  • 템플릿처럼 사용하기 위해 $로 시작하는 변수를 context변수로 사용한다.
  • 편의를 위해 t.loop, t.if 함수를 제공한다
    • t.loop역시 3가지 타잎의 파라메터를 받을 수 있고, Object파라메터의 key를 iteration되는 변수명으로, String 또는 Array 파라메터를 각각 루프영역의 innerHTML 또는 elements로써 활용한다. (중복되는 경우 Array를 우선 사용한다.)
    • TODO: Object파라미터의 요소가 2개 이상일 경우.. 중첩루프?
    • t.if도 3가지 파라메터를 가지고 cond를 키로 가지는 값을 Object를 평가식으로 사용한다. elseif, else 함수를 체인할 수 있다.

Pros

  • javascript 의 함수 호출 형식 그대로를 마크업에 사용할 수 있다.

Cons

  • 형제노드를 표현할때 항상 컴마를 붙여줘야 하기때문에 문법 오류 가능성이 높다.
  • 짧은 이름의 함수명을 대량으로 글로벌 영역에 만들어야 하므로 브라우져 구현은 t.div()와 같이 네임스페이스를 사용하게 된다. (보기에 좋지 않다)
  • class라는 어트리뷰트명은 대단히 많이 사용되지만 예약어이므로 항상 div({'class':'foo'})와 같이 따옴표로 이름을 감싸지 않으면 안된다.
html [
head [
meta charset: 'utf-8'
title 'syntax sample in coffee-script'
script src: 'jquery.min.js'
script "
$(function() {
console.log('dom ready!);
);
"
# inline comment
###
multiline
comment
###
]
body [
h1 $doctitle
t.loop $article: $articles, [
article [
h2 $article.title
div class: 'info', [
time data value: "2011-12-07"
]
p """
the article content
"""
br(), br()
"text node"
]
t.if(cond: $permission == "admin", [ # if syntax
div class: "admin", [
button "delete"
]
]).elseif(cond: $permission == "member", [
a href: '/login', 'Login'
]).else([
p "permission denied"
])
footer [
address "...all right reserved"
]
]
]
]
html([
head([
meta({charset:'utf-8'}),
title('syntax sample'),
script({src:'jquery.min.js'}),
script("
$(function() {
console.log('dom ready!');
});
")
// inline comment
/*
multiline
comment
*/
]),
body([
h1($doctitle), // variable
t.loop({$article : $articles}, [ // loop syntax
article([
h2($article.title),
div({class:'info'}, [
time([data({value:'2011-12-07'})])
]),
p("
the article content
"),
br(), br(),
"text node"
]),
t.if({cond: $permission == 'admin'}, [ // if syntax
div({class:'admin'}, [
button("delete")
])
]).elseif({cond: $permission == 'member'}, [
a({href: '/login'}, 'Login')
]).else([
p('Permission denied')
])
]),
footer([
address('...all right reserved')
])
])
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment