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
)
75 app
.use
("/", new MyTemplateHandler)
76 app
.use
("/string", new MyTemplateStringHandler)
77 app
.use
("/file", new MyTemplateFileHandler)
78 app
.listen
("localhost", 3000)