Created
September 4, 2011 14:10
-
-
Save pyykkis/1192901 to your computer and use it in GitHub Desktop.
Extremely simple js templates by convention: css class(+attribute) == json object field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
div A single activity | |
ul.activity | |
li.date | |
li.activity | |
li.comment | |
li.user | |
div Multiple activities | |
table | |
tr | |
th Date | |
th Activity | |
th Comment | |
th User | |
tr.activity | |
td.date | |
td | |
a.activity(href='#') | |
td.comment | |
td.user | |
:coffeescript | |
$ -> | |
# Get json from the server side or by user input | |
activity = | |
date: '2011-09-03' | |
activity: 'Running' | |
comment: 'Aamulenkki' | |
user: 'Jarno Keskikangas' | |
activities = [ | |
{ | |
id: '23453' | |
'activity@href': '/activities/23453' | |
date: '2011-09-03' | |
activity: 'Running' | |
comment: 'Aamulenkki' | |
user: 'Jarno Keskikangas' | |
}, { | |
id: '1232' | |
'activity@href': '/activities/1232' | |
date: '2011-09-03' | |
activity: 'Sänkypaini' | |
comment: 'Kovaa settiä' | |
user: 'Kari Peltola' | |
} | |
] | |
# Show da data | |
$('ul.activity').render(activity) | |
$('tr.activity').render(activities) | |
# I can haz cheeze burger? The first jQuery plugah | |
jQuery.fn.render = (data) -> | |
data = [data] unless $.isArray(data) | |
parent = this.parent() | |
template = this.clone() | |
this.remove() | |
_(data).each (object) -> | |
# Apply template for each object | |
template = template.clone() | |
_(object).chain().keys().each (key) -> | |
tmp = key.split('@') | |
klass = tmp[0] | |
attribute = tmp[1] if tmp.length > 1 | |
template.find(".#{klass}").each -> | |
if attribute | |
$(this).attr attribute, object[key] | |
else | |
$(this).text object[key] | |
parent.append(template) | |
return parent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment