浏览代码

debug mode updated, templates updated.

Ethosa 5 年之前
父节点
当前提交
b521e0fbdd
共有 4 个文件被更改,包括 44 次插入5 次删除
  1. 10 5
      akane/akane.nim
  2. 24 0
      tests/test4/main.nim
  3. 1 0
      tests/test4/nim.cfg
  4. 9 0
      tests/test4/templates/index.html

+ 10 - 5
akane/akane.nim

@@ -49,7 +49,7 @@ proc newServer*(address: string = "127.0.0.1",
   )
 
 
-proc loadtemplate*(name: string): Future[string] {.async, inline.} =
+proc loadtemplate*(name: string, json: JsonNode = %*{}): Future[string] {.async, inline.} =
   ## Loads HTML template from `templates` folder.
   ##
   ## Arguments:
@@ -58,6 +58,8 @@ proc loadtemplate*(name: string): Future[string] {.async, inline.} =
     file = openAsync(("templates" / name) & ".html")
     readed = await file.readAll()
   file.close()
+  for key, value in json.pairs:
+    readed = readed.replacef(re("(\\$\\s*\\(" & $key & "\\))"), $value)
   return readed
 
 
@@ -81,8 +83,13 @@ proc parseQuery*(request: Request): Future[JsonNode] {.async.} =
       hour = if now.hour > 9: $now.hour else: "0" & $now.hour
       minute = if now.minute > 9: $now.minute else: "0" & $now.minute
       second = if now.second > 9: $now.second else: "0" & $now.second
+      host =
+        if request.headers.hasKey("host") and request.headers["host"].len > 1:
+          request.headers["host"] & " "
+        else:
+          "new "
     echo(
-      "new ", request.reqMethod,
+      host, request.reqMethod,
       " at ", now.year, ".", month, ".", day,
       " ", hour, ":", minute, ":", second,
       " Request from ", request.hostname,
@@ -255,9 +262,7 @@ macro pages*(server: ServerRef, body: untyped): untyped =
       )
 
   result = newNimNode(nnkProcDef).add(
-    newNimNode(nnkPostfix).add(
-      ident("*"), ident("receivepages")  # procedure name.
-    ),
+    ident("receivepages"),  # procedure name.
     newEmptyNode(),  # for template and macros
     newEmptyNode(),  # generics
     newNimNode(nnkFormalParams).add(  # proc params

+ 24 - 0
tests/test4/main.nim

@@ -0,0 +1,24 @@
+# author: Ethosa
+# Working with templates.
+import akane
+
+
+proc main =  # main proc for gcsafe
+  var
+    server = newServer(debug=true)
+    data: JsonNode = %{
+      "myvariable": %0
+    }
+
+  server.pages:
+    equals("/"):  # when url is "domain/"
+      let index = await loadtemplate("index", data)
+      # all "$(myvariable)" in template file replaces at data["myvariable"]
+      data["myvariable"] = %(data["myvariable"].num + 1)
+      await request.answer(index)
+    notfound:
+      await request.error("<h1 align='center'>Sorry, but page not found :(</h1>")
+
+  server.start()  # Starts server.
+
+main()

+ 1 - 0
tests/test4/nim.cfg

@@ -0,0 +1 @@
+--path:"../../akane"

+ 9 - 0
tests/test4/templates/index.html

@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>Templates Test</title>
+</head>
+<body>
+  <h1 align="center">Now value is $(myvariable)</h1>
+</body>
+</html>