Browse Source

if stmt in templates.

SakiKawasaki 5 years ago
parent
commit
02f0b1d04c
3 changed files with 40 additions and 1 deletions
  1. 32 0
      akane/akane.nim
  2. 4 1
      tests/test4/main.nim
  3. 4 0
      tests/test4/templates/index.html

+ 32 - 0
akane/akane.nim

@@ -6,6 +6,7 @@ import asynchttpserver
 # ----- SUPPORT ----- #
 import asyncfile  # loadtemplate
 import strutils  # startsWith, endsWith
+import tables
 import macros
 import times
 import json  # urlParams
@@ -59,6 +60,37 @@ proc loadtemplate*(name: string, json: JsonNode = %*{}): Future[string] {.async,
     readed = await file.readAll()
   file.close()
   for key, value in json.pairs:
+    # if statment
+    # e.g.: if $(variable) {......}
+    var if_statment = re("if\\s*(\\$\\(" & key & "\\))\\s*\\{\\s*([\\s\\S]+?)\\s*\\}")
+    if readed.contains(if_statment):
+      var canplace: bool = false
+      case value.kind:
+      of JBool:
+        if value.getBool:
+          canplace = true
+      of JInt:
+        if value.getInt != 0:
+          canplace = true
+      of JFloat:
+        if value.getFloat != 0.0:
+          canplace = true
+      of JString:
+        if value.getStr.len > 0:
+          canplace = true
+      of JArray:
+        if value.len > 0:
+          canplace = true
+      of JObject:
+        if value.getFields.len > 0:
+          canplace = true
+      else: discard
+      if canplace:
+        readed = readed.replacef(if_statment, "$2")
+      else:
+        readed = readed.replacef(if_statment, "")
+    # variable statment
+    # e.g.: $(variable)
     readed = readed.replacef(re("(\\$\\s*\\(" & $key & "\\))"), $value)
   return readed
 

+ 4 - 1
tests/test4/main.nim

@@ -7,7 +7,8 @@ proc main =  # main proc for gcsafe
   var
     server = newServer(debug=true)
     data: JsonNode = %{
-      "myvariable": %0
+      "myvariable": %0,
+      "can_place": %false
     }
 
   server.pages:
@@ -15,6 +16,8 @@ proc main =  # main proc for gcsafe
       let index = await loadtemplate("index", data)
       # all "$(myvariable)" in template file replaces at data["myvariable"]
       data["myvariable"] = %(data["myvariable"].num + 1)
+      if data["myvariable"].num > 3:
+        data["can_place"] = %true
       await request.answer(index)
     notfound:
       await request.error("<h1 align='center'>Sorry, but page not found :(</h1>")

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

@@ -5,5 +5,9 @@
 </head>
 <body>
   <h1 align="center">Now value is $(myvariable)</h1>
+  if $(can_place)
+  {
+    <h1 align="center">Can plase is "true"</h1>
+  }
 </body>
 </html>