I created a simple web framework that uses the FastCGI protocol and works well. But, it is being complicated to manage so many route functions in a single file. I was wondering if there is a keyword in Nim like in php to insert code from another file in the main code.
Example:
import fastkiss
import tables
from strutils import `%`
import routes/fuction_show_page.nim # to insert the code above
#
#-- begin: this code in another file (routes/fuction_show_page.nim) --
#
proc showPage(req: Request) {.async.} =
let t = {1: "one", 2: "two", 3: "three"}.toTable
"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
</head>
<body>
<table>""".resp
for k, v in pairs(t):
resp """<tr>
<td><strong>$1</strong></td>
<td>$2</td>
</tr>
""" % [$k, v]
"""</table>
</body>
</html>""".resp
#
#-- end --
#
proc main() =
let app = newApp()
app.get("/", showPage)
app.run()
main()
Is this the best way to segment the code of an application? Hey!
Yes, Nim has an include keyword which behaves much like in C or PHP. See: include statement
So you could do this:
import fastkiss
import tables
from strutils import `%`
include "routes/function_show_page.nim"
proc main() =
let app = newApp()
app.get("/", showPage)
app.run()
main()
In your case, you might also find Nim's built-in templating system stdtmpl to be useful.
It works by preprocessing the file before including it. Any line that starts with # will be treated as Nim code. Any line that doesn't start with # will be treated as text output.
You can use it like this:
routes/function_show_page.html.template
#? stdtmpl(emit="resp") | standard
#proc showPage(req: Request) {.async.} =
# let t = {1: "one", 2: "two", 3: "three"}.toTable
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
</head>
<body>
<table>
#for k, v in pairs(t):
<tr>
<td><strong>$k</strong></td>
<td>$v</td>
</tr>
#end for
</table>
</body>
</html>
main.nim
import fastkiss
import tables
from strutils import `%`
include "routes/function_show_page.html.template"
proc main() =
let app = newApp()
app.get("/", showPage)
app.run()
main()
Thanks @kobi for your help. It was the first thing I tried, but not work!
Error: undeclared identifier: 'Request'
To work I have to import many things. The "include" statement works as I expected.