cowboy的动态页用的是erlydtl,需要先安装erlydtl模板引擎,或者你在dep里面添加
创建工程
rebar-creator create-app testCowboy
testCowboy_app.erl
-module(testCowboy_app). -behaviour(application). -export([start/, stop/]). -define(C_ACCEPTORS, ). start(_StartType, _StartArgs) ->
application:start(crypto),
application:start(cowlib),
application:start(ranch),
application:start(cowboy), application:start(gproc),
application:start(uuid),
application:start(cowboy_session), Routes = route_helper:get_routes(),
Dispatch = cowboy_router:compile(Routes),
Port = ,
TransOpts = [{port, Port}],
ProtoOpts = [
{env, [
{dispatch, Dispatch}]}
],
cowboy:start_http(http, ?C_ACCEPTORS, TransOpts, ProtoOpts). stop(_State) ->
ok.
route_helper.erl
-module(route_helper). -export([get_routes/]). get_routes() ->
[
{'_', [
{"/dtl", dtl_handler, []}
]}
].
dtl_handler.erl
-module(dtl_handler). -export([init/]).
-export([handle/]).
-export([terminate/]). init(_Transport, Req, []) ->
{ok, Req, undefined}. handle(Req, State) ->
%% 这里的toppage_dtl是我们编译好的模板名
%% erlydtl:compile_file("../templates/toppage.dtl", toppage_dtl).
{ok, Body} = toppage_dtl:render([
{client, <<"Client123">>},
{server, <<"Server123">>}
]),
{ok, Req2} = cowboy_req:reply(,
[{<<"content-type">>, <<"text/html">>}],
Body, Req),
{ok, Req2, State}. terminate(_Reason, _Req, _State) ->
ok.
toppage.dtl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cowboy Cookie Example</title>
</head> <body>
<h1>Cowboy Cookie Example</h1>
<p>Refresh the page to see the next cookie.</p> <h2>Cookie Set Server-Side</h2>
<p>{{ server }}</p> <h2>Cookie Set Client-Side</h2>
<p>{{ client }}</p> <script type="text/javascript">
// <![CDATA[
document.cookie="client=test=";
// ]]>
</script>
</body>
</html>
这里注意,在build的时候,需要先编译模板
erlydtl:compile_file("../templates/toppage.dtl", toppage_dtl).
简单弄了个编译脚本
rebar clean;
erl -eval 'erlydtl:compile_file("./templates/toppage.dtl", toppage_dtl,[{out_dir,"./ebin"}]).' -noshell -s init stop;
rebar compile;
我的目录
mac:testCowboy mmc$ tree
.
├── build.sh
├── src
│ ├── dtl_handler.erl
│ ├── route_helper.erl
│ ├── testCowboy.app.src
│ └── testCowboy_app.erl
└── templates
└── toppage.dtl
试试看看,现在是不是可以了
注:dtl模板编译以后就是beam,所以,修改动态页面以后,模板需要重新编译并且load