]> gitweb.factorcode.org Git - factor.git/blob - basis/html/templates/templates.factor
fd48d81ecdfa12aba967e66fd73ce5b71c3bd41e
[factor.git] / basis / html / templates / templates.factor
1 ! Copyright (C) 2008, 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors kernel fry io io.encodings.utf8 io.files
4 debugger prettyprint continuations namespaces boxes sequences
5 arrays strings html io.streams.string assocs
6 quotations xml.data xml.writer xml.syntax ;
7 IN: html.templates
8
9 MIXIN: template
10
11 GENERIC: call-template* ( template -- )
12
13 M: string call-template* write ;
14
15 M: callable call-template* call( -- ) ;
16
17 M: xml call-template* write-xml ;
18
19 M: object call-template* output-stream get stream-copy ;
20
21 ERROR: template-error template error ;
22
23 M: template-error error.
24     "Error while processing template " write
25     [ template>> short. ":" print nl ]
26     [ error>> error. ]
27     bi ;
28
29 : call-template ( template -- )
30     [ call-template* ] [ \ template-error boa rethrow ] recover ;
31
32 ERROR: no-boilerplate ;
33
34 M: no-boilerplate error.
35     drop
36     "get-title and set-title can only be used from within" print
37     "a with-boilerplate form" print ;
38
39 SYMBOL: title
40
41 : set-title ( string -- )
42     title get [ >box ] [ no-boilerplate ] if* ;
43
44 : get-title ( -- string )
45     title get [ value>> ] [ no-boilerplate ] if* ;
46
47 : write-title ( -- )
48     get-title write ;
49
50 SYMBOL: style
51
52 : add-style ( string -- )
53     "\n" style get push-all
54          style get push-all ;
55
56 : get-style ( -- string )
57     style get >string ;
58
59 : write-style ( -- )
60     get-style write ;
61
62 SYMBOL: atom-feeds
63
64 : add-atom-feed ( title url -- )
65     2array atom-feeds get push ;
66
67 : get-atom-feeds ( -- xml )
68     atom-feeds get [
69         [XML
70             <link
71                 rel="alternate"
72                 type="application/atom+xml"
73                 title=<->
74                 href=<->/>
75         XML]
76     ] { } assoc>map ;
77
78 : write-atom-feeds ( -- )
79     get-atom-feeds write-xml ;
80
81 SYMBOL: nested-template?
82
83 SYMBOL: next-template
84
85 : call-next-template ( -- )
86     next-template get write ;
87
88 M: f call-template* drop call-next-template ;
89
90 : with-boilerplate ( child master -- )
91     [
92         title [ <box> or ] change
93         style [ SBUF" " clone or ] change
94         atom-feeds [ V{ } like ] change
95
96         [
97             [
98                 nested-template? on
99                 call-template
100             ] with-string-writer
101             next-template set
102         ]
103         [ call-template ]
104         bi*
105     ] with-scope ; inline
106
107 : template-convert ( template output -- )
108     utf8 [ call-template ] with-file-writer ;