1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2017 Alexandre Terrasa <alexandre@moz-code.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
18 import popcorn
::pop_templates
20 class MyTemplateHandler
24 var template
= new TemplateString("""
25 <h1>Hello %USER%!</h1>
26 <p>Welcome to %MYSITE%.</p>
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"
36 res
.template
(template
, values
)
40 class MyTemplateStringHandler
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"
49 # Render it with a shortcut
50 res
.template_string
("""
51 <h1>Hello %USER%!</h1>
52 <p>Welcome to %MYSITE%.</p>
57 class MyTemplateFileHandler
60 # Use template from external file
61 var tpl_file
= "example_template.tpl"
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"
69 # Render it from an external file
70 res
.template_file
(tpl_file
, values
)
74 class MyTemplatePugHandler
77 redef fun get
(req
, res
) do
78 # Values to add in the template
79 var json
= new JsonObject
80 json
["user"] = "Morriar"
81 json
["mysite"] = "My super website"
85 p Welcome to #{mysite}
90 class MyTemplatePugFileHandler
93 # Use template from external file
94 var pug_file
= "example_template.pug"
96 redef fun get
(req
, res
) do
97 # Values to add in the template
98 var json
= new JsonObject
99 json
["user"] = "Morriar"
100 json
["mysite"] = "My super website"
102 # Render it from an external file
103 res
.pug_file
(pug_file
, json
)
108 app
.use
("/", new MyTemplateHandler)
109 app
.use
("/string", new MyTemplateStringHandler)
110 app
.use
("/file", new MyTemplateFileHandler)
111 app
.use
("/pug", new MyTemplatePugHandler)
112 app
.use
("/pug_file", new MyTemplatePugFileHandler)
113 app
.listen
("localhost", 3000)