802dd4b6e49f8e6873f8a5a5d0f0f7d9bf4ab763
[nit.git] / lib / popcorn / pop_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 module pop_templates
18
19 import popcorn::pop_handlers
20 import template::macro
21
22 redef class HttpResponse
23
24 # Render the TemplateString `tpl` with `values` and write it as html.
25 fun template(tpl: nullable TemplateString, values: nullable Map[String, nullable Writable], status: nullable Int) do
26 if tpl != null and values != null then
27 for k, v in values do
28 if not tpl.has_macro(k) or v == null then continue
29 tpl.replace(k, v)
30 end
31 end
32 html(tpl, status)
33 end
34
35 # Render `file` as a TemplateString with `values` and write it as html.
36 fun template_string(tpl_string: nullable String, values: nullable Map[String, nullable Writable], status: nullable Int) do
37 var tpl = new TemplateString(tpl_string or else "")
38 template(tpl, values, status)
39 end
40
41 # Render `file` as a TemplateString with `values` and write it as html.
42 fun template_file(file: String, values: nullable Map[String, nullable Writable], status: nullable Int) do
43 var tpl = new TemplateString.from_file(file)
44 template(tpl, values, status)
45 end
46
47 # Render `pug_string` with the command cli `pug` and use data from `json`
48 #
49 # See https://pugjs.org/api/getting-started.html for more details on pug.
50 fun pug(pug_string: nullable String, json: nullable Serializable, status: nullable Int) do
51 var process
52 if json == null then
53 process = new ProcessDuplex("pug", "-D")
54 else
55 process = new ProcessDuplex("pug", "-D", "-O", json.to_json)
56 end
57 var out = process.write_and_read(pug_string or else "")
58 process.close
59 html(out, status)
60 end
61
62 # Render `file` with the command cli `pug` and use data from `json`
63 #
64 # See https://pugjs.org/api/getting-started.html for more details on pug.
65 fun pug_file(file: String, json: nullable Serializable, status: nullable Int) do
66 pug(file.to_path.read_all, json, status)
67 end
68 end