pep8analysis: intro the web interface
[nit.git] / lib / template.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Basic template system
16 #
17 # The recommended usage of this framework is to define specific subclasses of
18 # Template to provide structural elements on the final document
19 module template
20
21 # Templates are simple hierarchical pieces of text used for efficient stream writing.
22 #
23 # # Efficient stream writing
24 #
25 # Templates are more efficient than ever-growing buffers with useless concatenation
26 # and more usable and maintainable than manual arrays of strings.
27 #
28 # The `add` method (and its variations) is used to append new content (like string or
29 # other templates) to a template object.
30 #
31 # Eventually, the `write_to` method (and its variations) is used to write the complete
32 # content of a template in streams (and files, and strings).
33 #
34 # var tmpl = new Template
35 # tmpl.add("A")
36 # tmpl.add("B")
37 # tmpl.add("C")
38 # assert tmpl.write_to_string == "ABC"
39 #
40 # # Non-linear system with sub-templates.
41 #
42 # A template is made of a mix of string, sub-templates and other `Streamable` objects.
43 # A sub-template can be constructed independently of its usages, thus simplifying
44 # the high-level logic.
45 # A single sub-template can be used more than once.
46 #
47 # var main = new Template
48 # var sub = new Template
49 # sub.add("1")
50 # main.add("A")
51 # main.add(sub)
52 # main.add("B")
53 # main.add(sub)
54 # main.add("C")
55 # sub.add("2")
56 # assert main.write_to_string == "A12B12C"
57 #
58 # See also the `new_sub` method.
59 #
60 # # Specific high-level templates
61 #
62 # The advanced, and recommended way, is to subclass Template and provide an autonomous
63 # structural template with its specific attributes and templating logic.
64 #
65 # In such a subclass, the full logic is provided by the `rendering` method that will
66 # be automatically and lazily invoked.
67 #
68 # class LnkTmpl
69 # super Template
70 # var text: Streamable
71 # var title: nullable String
72 # var href: String
73 # redef fun rendering do
74 # add """<a href="{{{href.html_escape}}}""""
75 # if title != null then add """ title="{{{title.html_escape}}}""""
76 # add ">"
77 # add text
78 # add "</a>"
79 # end
80 # # ...
81 # end
82 # var l = new LnkTmpl("hello world", null, "hello.png")
83 # assert l.write_to_string == """<a href="hello.png">hello world</a>"""
84 #
85 class Template
86 super Streamable
87
88 # Service used to render the content of the template.
89 #
90 # Do nothing by default but subclasses should put all their specific
91 # templating code in this method to regroup and simplify their logic
92 #
93 # Note: to avoid inconsistencies, the template is automatically frozen
94 # (see `freeze`) after the invocation of `rendering`.
95 protected fun rendering do end
96
97 # Append an element (`String`, other `Template`, etc.) at the end of the template.
98 #
99 # Should be either used externally to act on basic templates,
100 # or internally in the `rendering` method of specific templates.
101 #
102 # Mixing the internal and external uses should be avoided because
103 # the final behavior will depend on the lazy invocation of `rendering`.
104 #
105 # var t = new Template
106 # t.add("1")
107 # t.add("2")
108 # assert t.write_to_string == "12"
109 fun add(element: Streamable) do
110 assert not is_frozen
111 content.add element
112 end
113
114 # Append a bunch of elements at the end of the template.
115 # See `add`.
116 #
117 # var t = new Template
118 # t.add_all(["1", "2"])
119 # assert t.write_to_string == "12"
120 fun add_all(elements: Collection[Streamable]) do content.add_all elements
121
122 # Append a bunch of elements at the end of the template with separations.
123 # see `add`.
124 #
125 # var t = new Template
126 # t.add_list(["1", "2", "3"], ", ", " and ")
127 # assert t.write_to_string == "1, 2 and 3"
128 fun add_list(elements: Collection[Streamable], sep, last_sep: Streamable) do
129 var last = elements.length - 2
130 var i = 0
131 for e in elements do
132 content.add e
133 if i < last then
134 content.add sep
135 else if i == last then
136 content.add last_sep
137 end
138 i += 1
139 end
140 end
141
142 # Is the template allowing more modification (`add`)
143 var is_frozen = false
144
145 # Disable further modification: no more `add` is allowed
146 fun freeze
147 do
148 if is_frozen then return
149 is_frozen = true
150 end
151
152 # Return a new basic template that is automatically added in `self` (using `add`)
153 #
154 # This is an easy way to provide a free insertion point in an existing template.
155 #
156 # var t = new Template
157 # t.add("""void main(void) {""")
158 # var tdecl = t.new_sub # used to group declarations
159 # tdecl.add("int i; ")
160 # t.add("i = 1; ")
161 # tdecl.add("int j; ")
162 # t.add("j = i + 1; ")
163 # t.add("\}")
164 # assert t.write_to_string == """void main(void) {int i; int j; i = 1; j = i + 1; }"""
165 fun new_sub: Template
166 do
167 var res = new Template
168 add res
169 return res
170 end
171
172 # Each sub-elements
173 private var content = new Array[Streamable]
174
175 # Flag to avoid multiple rendering
176 private var render_done = false
177
178 # Call rendering, if not already done
179 # Then freeze the template
180 #
181 # This method is only required in corner-cases since
182 # `rendering` is automatically called when needed.
183 fun force_render
184 do
185 if render_done then return
186 render_done = true
187 rendering
188 freeze
189 end
190
191 # Do the full rendering and write the final content to a stream
192 redef fun write_to(stream: OStream)
193 do
194 assert not is_writing
195 is_writing = true
196 force_render
197 for e in content do
198 e.write_to(stream)
199 end
200 is_writing = false
201 end
202
203 # Flag to avoid infinite recursivity if a template contains itself
204 private var is_writing = false
205 end