lib/popcorn: introduce basic templates
[nit.git] / lib / popcorn / examples / templates / example_templates.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2017 Alexandre Terrasa <alexandre@moz-code.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import popcorn
18 import popcorn::pop_templates
19
20 class MyTemplateHandler
21 super Handler
22
23 # Template to render
24 var template = new TemplateString("""
25 <h1>Hello %USER%!</h1>
26 <p>Welcome to %MYSITE%.</p>
27 """)
28
29 redef fun get(req, res) do
30 # Values to add in the template
31 var values = new HashMap[String, String]
32 values["USER"] = "Morriar"
33 values["MYSITE"] = "My super website"
34
35 # Render it
36 res.template(template, values)
37 end
38 end
39
40 class MyTemplateStringHandler
41 super Handler
42
43 redef fun get(req, res) do
44 # Values to add in the template
45 var values = new HashMap[String, String]
46 values["USER"] = "Morriar"
47 values["MYSITE"] = "My super website"
48
49 # Render it with a shortcut
50 res.template_string("""
51 <h1>Hello %USER%!</h1>
52 <p>Welcome to %MYSITE%.</p>
53 """, values)
54 end
55 end
56
57 class MyTemplateFileHandler
58 super Handler
59
60 # Use template from external file
61 var tpl_file = "example_template.tpl"
62
63 redef fun get(req, res) do
64 # Values to add in the template
65 var values = new HashMap[String, String]
66 values["USER"] = "Morriar"
67 values["MYSITE"] = "My super website"
68
69 # Render it from an external file
70 res.template_file(tpl_file, values)
71 end
72 end
73
74 var app = new App
75 app.use("/", new MyTemplateHandler)
76 app.use("/string", new MyTemplateStringHandler)
77 app.use("/file", new MyTemplateFileHandler)
78 app.listen("localhost", 3000)