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.
17 module example_templates
is example
20 import popcorn
::pop_templates
22 class MyTemplateHandler
26 var template
= new TemplateString("""
27 <h1>Hello %USER%!</h1>
28 <p>Welcome to %MYSITE%.</p>
31 redef fun get
(req
, res
) do
32 # Values to add in the template
33 var values
= new HashMap[String, String]
34 values
["USER"] = "Morriar"
35 values
["MYSITE"] = "My super website"
38 res
.template
(template
, values
)
42 class MyTemplateStringHandler
45 redef fun get
(req
, res
) do
46 # Values to add in the template
47 var values
= new HashMap[String, String]
48 values
["USER"] = "Morriar"
49 values
["MYSITE"] = "My super website"
51 # Render it with a shortcut
52 res
.template_string
("""
53 <h1>Hello %USER%!</h1>
54 <p>Welcome to %MYSITE%.</p>
59 class MyTemplateFileHandler
62 # Use template from external file
63 var tpl_file
= "example_template.tpl"
65 redef fun get
(req
, res
) do
66 # Values to add in the template
67 var values
= new HashMap[String, String]
68 values
["USER"] = "Morriar"
69 values
["MYSITE"] = "My super website"
71 # Render it from an external file
72 res
.template_file
(tpl_file
, values
)
76 class MyTemplatePugHandler
79 redef fun get
(req
, res
) do
80 # Values to add in the template
81 var json
= new JsonObject
82 json
["user"] = "Morriar"
83 json
["mysite"] = "My super website"
87 p Welcome to #{mysite}
92 class MyTemplatePugFileHandler
95 # Use template from external file
96 var pug_file
= "example_template.pug"
98 redef fun get
(req
, res
) do
99 # Values to add in the template
100 var json
= new JsonObject
101 json
["user"] = "Morriar"
102 json
["mysite"] = "My super website"
104 # Render it from an external file
105 res
.pug_file
(pug_file
, json
)
110 app
.use
("/", new MyTemplateHandler)
111 app
.use
("/string", new MyTemplateStringHandler)
112 app
.use
("/file", new MyTemplateFileHandler)
113 app
.use
("/pug", new MyTemplatePugHandler)
114 app
.use
("/pug_file", new MyTemplatePugFileHandler)
115 app
.listen
("localhost", 3000)