Starting Mojolicious #2
Mojolicious::Liteのチュートリアルを読み進めるだけではあまり面白くなかったので、Yahoo TopicsのRSSを表示するかんたんなウェブアプリを書いてみた。
#!/usr/bin/env perl use utf8; use Mojolicious::Lite; use XML::Feed; use URI; get '/' => sub { my $self = shift; $self->render('index'); }; get '/topics/:genre' => sub { my $self = shift; my $genre = $self->param('genre'); my $url = "http://rss.dailynews.yahoo.co.jp/fc/$genre/rss.xml"; my $feed = XML::Feed->parse( URI->new($url) ); $self->stash(title => $feed->title, entries => [ $feed->entries ]); $self->render('topics'); }; app->start; __DATA__ @@ index.html.ep % layout 'default'; % title 'Welcome!'; <h1>Yahoo Topics RSS</h1> <ul> <li><a href="/topics/world">海外</a></li> <li><a href="/topics/computer">コンピューター</a></li> <li><a href="/topics/sports">スポーツ</a></li> </ul> @@ topics.html.ep % layout 'default'; % title 'Yahoo Topics RSS'; <h1><%= $title %> - RSS</h1> <ul> % for my $item (@$entries) { <li><a href="<%= $item->link %>"><%= $item->title %></a></li> % } </ul> @@ layouts/default.html.ep <!DOCTYPE html> <html> <head> <title><%= title %></title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body><%= content %></body> </html>
あとは
plackup app.psgi
だけで使えるようになる。
小さいウェブアプリ書く時にはMojolicious::Liteが第一選択肢になるかも。