介紹一個nim語言的web template

 

nimWebTemplates   https://github.com/enthus1ast/nimWebTemplates

nimWebTemplates這個東西, 是一個簡單的類似於django 的template , 類似於jinja2的模板, 有 block, end, extends, for, if之類的標籤. 

大部分的東西, 都是2年前的, 最近的修改是5個月前的. nim的項目作者都是這樣, 要不就是5年前的作品放在那裏等人挖墳, 要不就是作者詐屍彈起來突然更新一下. 

usage

目錄結構

創建如下目錄結構(注: 作者目前只支持單層目錄, 2層目錄的不支持, 我擴展了, 很簡單, 現在還沒發出來.)

./example.nim
./templates/base.html
./templates/index.html
./templates/about.html
./templates/stats.html

menu.html

{%block menu%}<a href="index.html">index</a> || <a href="about.html">about</a> || <a href="stats.html">stats</a>{%endblock%}

base.html

{%import menu.html%}
<html>
	<head>
		<title>{{title}}</title>
	</head>

	<body>
		<div>
			{{self.menu}} 

		</div>

		<h1>{{title}}</h1>

		<div>
			{%block "content"%}
				{# i will be replaced by my children #}
			{%endblock%}
		</div>

		<div>
			<hr> 
			Made with nim<br>
			{{self.footer}}
		</div>
	</body>
</html>

example.nim 


import asynchttpserver, asyncdispatch
import json
import nwt

var templates = newNwt("templates/*.html") # we have all the templates in a folder called "templates"

var server = newAsyncHttpServer()
proc cb(req: Request) {.async.} =
  let res = req.url.path

  case res 
  of "/", "/index.html":
    await req.respond(Http200, templates.renderTemplate("index.html"))  
  of "/about.html":
    await req.respond(Http200, templates.renderTemplate("about.html"))
  of "/stats.html":
    var context = %* {"title": "some variables from nim", "foo": "Foo!", "baa": "Baa!"}
    await req.respond(Http200, templates.renderTemplate("stats.html", context))  
  else:
    await req.respond(Http404, "not found")

waitFor server.serve(Port(8080), cb) 

基本上, 基於example.nim, 就可以開發一個同步的web 框架了. 我就是在這個的基礎上, 加了很多東西, 寫了以簡單的nim語言的web框架

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章