-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdot_core.coffee
70 lines (59 loc) · 1.76 KB
/
dot_core.coffee
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class DotCore
constructor: (settings = {}) ->
@autoload = @constructor.autoloadDOM()
@cache = {}
@[key] = val for key, val of settings
# template compilation
compile: (tmpl, compileParams = {}) ->
compileParams.def ||= {}
compileParams.doT ||= @
mangles_list = Object.keys(@mangles).sort()
for m_id, m_name of mangles_list
tmpl = @mangles[m_name].call compileParams, tmpl, compileParams
tmpl
# cache functions
getCached: (tmpl) ->
return @cache unless tmpl
throw new Error "Template not found: #{tmpl}" unless @cache[tmpl]
@cache[tmpl]
setCached: (@cache) ->
exportCached: ->
str = ""
str += ",\"#{id}\": #{f.toString()}" for id, f of @cache
"{#{str[1..]}}"
addCached: (id, fn) ->
if 'object' == typeof id
@cache[i] = f for i, f of id
else
@cache[id] = fn
@
# #render() for transparent autoloding & caching
render: (tmpl) ->
tmpl = name: tmpl unless 'object' == typeof tmpl
fn = null
unless fn = @cache[tmpl.name]
if false == src = @autoload tmpl.name
throw new Error "Template not found: #{tmpl.name}"
@addCached tmpl.name, fn = @compile src
fn.apply @, tmpl.args || Array::slice.call arguments, 1
# autoload implementations
@autoloadDOM: (opts) -> (name) ->
src = document.getElementById name
return false unless src?.type is 'text/x-dot-tmpl'
src.innerHTML
@autoloadFS: (opts) ->
opts.fs ||= require 'fs'
(name) ->
try
opts.fs.readFileSync "#{opts.root}/#{name.replace('.', '/')}.tmpl"
catch e
false
@autoloadFail: -> false
autoload: @autoloadFail
# register in global scope
if module?.exports
module.exports = DotCore
else if define?.amd
define -> DotCore
else
@DotCore = DotCore