编写你的第一个Mojolicious应用

Mojolicious是下一代Perl开源Web框架,和Node Sails.js、Express.js、Koa.js,Python Django、Flask,Ruby on Rails等类似,它也是mvc框架。虽然它应用不广泛,不过如果熟悉其他mvc框架,你会很快熟悉它的。

安装Mojolicious很简单,运行以下命令:

$ sudo curl -L https://cpanmin.us | sudo perl - -M https://cpan.metacpan.org -n Mojolicious

另外使用mojo命令可以快速生成Web应用原型。

Youtube有个介绍Mojoliciou的视频,作者为mojocasts,视频覆盖了Mojolicious的基础内容,视频中的例子如下:

app.pl

#!/usr/bin/env perl

use Mojolicious::Lite;

get '/' => sub {
  shift->render('hello');
};

get '/:fullname' => sub {
  my $self = shift;

  $self->stash(
    fullname => uc $self->param('fullname')
  );
  
  $self->render('capture');
};

app->start;

__DATA__

@@ layouts/wrapper.html.ep
<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
</head>
<body>
  <h1><%= title %></h1>
  <%= content %>To the flying maching
</body>
</html>

@@ hello.html.ep
hello, this is my first Mojolicious web app

@@ capture.html.ep
% title 'Planet Express';
% layout 'wrapper';
hello <%= $fullname %>

执行如下命令:

$ mkdir log # optional
$ morbo app.pl

其中morbo是perl写的web服务器。

打开浏览器,访问“localhost:3000/your full name”:

Mojolicious-hello-demo
Mojolicious-hello-demo

参考:

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s