Mojolicious模板渲染(一)

前面我已经讲了Mojolicious单文件项目开发,mojolicious如何使用mysql数据库。讲完这两部分,对于写一个简单增删改查的项目来说,还缺少一样——前端页面的开发。

本部分参考资料来自metacpan的Mojolicious::Guides::Rendering。

一、Render渲染器

首先我们要来看看渲染器中的各种表达方式:

use Mojolicious::Lite -signatures;

# /hello
# /hello/Sara
get '/hello/:name' => {name => 'Sebastian', day => 'Monday'} => sub ($c) {
  $c->render(template => 'groovy', format => 'txt');
};

app->start;
__DATA__

@@ groovy.txt.ep
My name is <%= $name %> and it is <%= $day %>.

还记得吗?这是我在Mojolicious初学中讲到的一个单文件项目的例子。其中$c->render便是渲染器,而我今天要讲的表达方式,便是render渲染器中的键值对参数:

{text => 'Hello.'} -> 200 OK, text/html, 'Hello.'
{json => {x => 3}} -> 200 OK, application/json, '{"x":3}'
{text => 'Oops.', status => '410'} -> 410 Gone, text/html, 'Oops.'

前面花括号表示的我们在render渲染器中放入的参数,->之后放置的是服务器返回给浏览器的数据状态、格式、内容。

请回忆一下Mojolicious初学篇中,我讲过,如果我们的路由和html模板的名称是对应的,Mojo应用会自动的检测到模板。模板的名字要遵循template.format.handler的格式,即模板名称.返回数据格式.句柄,其中template模板一般是controller/action或者路由,format格式默认为html,handler句柄一般指的ep,嵌入式perl语言的简称:

{controller => 'users', action => 'list'} -> 'users/list.html.ep'
{template => 'foo', format => 'txt'} -> 'foo.txt.ep'
{template => 'foo', handler => 'epl'} -> 'foo.html.epl'

其中controller和action这两个词中,controller指mojo里面一种特殊的perl模块文件,action是该模块文件中的sub方法。controller/action结构后面我讲多文件,也就是大型项目的文件结构时会用到。

controller的表示方法,mojo会通过mojo::util模块的decamelize方法进行自动适配:

{controller => 'My::Users', action => 'add'} -> 'my/users/add.html.ep'
{controller => 'my-users', action => 'show'} -> 'my/users/show.html.ep'

关于template的内容如mojolicious初学中讲的,可以放在templates文件夹下,也可以放在__DATA__代码块中:

__DATA__

@@ time.html.ep
% use Time::Piece;
% my $now = localtime;
<!DOCTYPE html>
<html>
  <head><title>Time</title></head>
  <body>The time is <%= $now->hms %>.</body>
</html>

@@ hello.txt.ep
...

 

 

标签