Mojolicious::Liteのメモ

2015年7月20日

Mojolicious::Liteでアプリを作ろうと思ったらど忘れしてたのでメモ

$ mkdir myapp
$ cd myapp
$ mojo generate lite_app APP_NAME.pl

これでカレントディレクトリにAPP_NAME.plが生成される
中身は以下の通り

#!/usr/bin/env perl
use Mojolicious::Lite;

# Documentation browser under "/perldoc"
plugin 'PODRenderer';

get '/' => sub {
  my $c = shift;
  $c->render(template => 'index');
};

app->start;
__DATA__

@@ index.html.ep
% layout 'default';
% title 'Welcome';
Welcome to the Mojolicious real-time web framework!

@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
  <head><title><%= title %></title></head>
  <body><%= content %></body>
</html>

cssやテンプレートを保存するディレクトリを作る

$ mkdir -p templates/root/
$ mkdir -p templates/layouts/
$ mkdir -p public/css

上記を作ったらまずテンプレートをAPP_NAME.plから分割

$ cat templates/root/index.html.ep
% layout 'default';
% title 'Welcome';
Welcome to the Mojolicious real-time web framework!

$ cat templates/layouts/default.html.ep
<!DOCTYPE html>
<html>
  <head><title><%= title %></title></head>
  <body><%= content %></body>
</html>

これでテンプレートは自動的にtemplatesディレクトリ以下から適宜読み込まれる。
cssに関してはpublic/css以下に保存したファイルをテンプレートの中からstyleタグ、もしくはlinkタグで読み込める

アプリの実行は

morbo APP_NAME.pl

でOK

あと、
作業していてhtmlタグのヘルパーが公式リファレンスのどこを探せばいいのか迷ったのであげとく
Mojolicious::Plugin::TagHelpers

そしてsassを使いたいときは次の記事を参照
Mojoliciousでsassを使う

追記

templatesディレクトリに**.html.epを分割した時は、呼び出し元のソースのrender関数を修正する必要があるかも

get '/' => sub {
    my $c = shift;

    $c->render(template => 'root/index');
};

もしくは

    $c->render();
} => 'root/index';