1. 程式人生 > >openresty 前端開發輕量級MVC框架封裝二(渲染篇)

openresty 前端開發輕量級MVC框架封裝二(渲染篇)

這一章主要介紹怎麼使用模板,進行後端渲染,主要用到了lua-resty-template這個庫,直接下載下來,放到lualib裡面就行了,推薦第三方庫,已經框架都放到lualib目錄裡面,lua目錄放專案原始碼,比較好管理,可以知道那些是專案的,哪些是第三方庫,可複用的

下載解壓到lualib目錄之後,就算安裝完成了,下面來試用一下,更詳細的可以到github上面看文件

conf/nginx.conf


worker_processes  1;

error_log logs/error.log notice;

events {
    worker_connections 1024;
}

http {
    lua_package_path "/Users/john/opensource/openresty-web-dev/demo9/lua/?.lua;/Users/john/opensource/openresty-web-dev/demo9/lualib/?.lua;/usr/local/openresty/lualib/?.lua"
; server { listen 80; server_name localhost; lua_code_cache off; location / { root lua; # 這個很重要,不然模板檔案會找不到 default_type "text/html; charset=utf-8"; content_by_lua_file lualib/lite/mvc.lua; } location ~ ^/js/|^/css/|\.html { root html; } } }

lua/index.lua

local template = require "resty.template"

local _M = {}

function _M.index()
    local model = {title = "hello template", content = "<h1>content</h1>"}
    -- 1、外部模板檔案
    -- template.render('tpl/index.html', model)
    -- 2、內嵌模板程式碼
    template.render([[
<html>
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
    {* content *}
</body>
</html>
        ]]
, model) end return _M

lua/tpl/index.html

<html>
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>
    {* content *}
</body>
</html>

跟spring mvc 有點像,指定一個 view , model,然後就可以渲染了,模板語法有很多種,{{ 變數 }} 會進行轉義,{* 不會轉義 *},{% lua 程式碼 %},跟jsp有點類似,但是很輕量,只有單個檔案,更多用法可以到github上面看。

至此,服務端渲染就搞定了,已經可以開發一些常見的web應用,使用openresty來做前端,然後通過http訪問後端的java,也可以在前端,直接訪問mysql、redis,只不過mysql只能做一些簡單的非事務操作,因為lua-resty-mysql這個庫不支援事務,我在github上面問過春哥了,當然如果你直接呼叫儲存過程,把事務放在過程裡面控制的話也可以,現在你可以直接寫同步的程式碼風格,就能獲得高併發、低消耗,非堵塞等各種好處。

我們已經用openresty開發了pc版,還有微信版的web應用,已經執行幾個月了,很穩定,上手也簡單,開發的時候不用編譯,直接啟動一個nginx就搞定,部署的時候只需要10幾M的記憶體,還可以用openresty做各種事情,高併發api、web防火牆,直接跑在nginx裡面,簡直爽歪歪,有機會跟大家分享。

示例程式碼 參見demo9部分