perlプログラムを実行してテンプレートファイルを読み込むことができます。
まず書いとくものは、下記のようなものです。
「app/controller/test.pl」
use MENTA::Controller; sub run { }
run関数内に処理を記述していきます。
use MENTA::Controller; sub run { render_and_print('test.mt'); }
render_and_printは、テンプレートファイルを基に、HTMLを出力する関数です。
第一引数はテンプレート名です。
第二引数以降に、テンプレートに渡す値を書いていきます。
use MENTA::Controller; sub run { render_and_print('test.mt','test1','test2'); }
テンプレート側では下記のように受け取ります。
? my ($test1, $test2) = @_; <html> <head><title>test</title></head> <body> 第一引数:<?= $test1 ?><br> 第二引数:<?= $test2 ?><br> </body> </html>
サーバを起動して「http://localhost:5555/test」にアクセスすれば結果が見れます。
テンプレートにうまく引数が渡らない件
ここで、CPANモジュールの「Text::MicroTemplate::File」のバージョンによっては、うまく動きません。
下記のようなエラーが出てくるかもしれません。
Can't call method "_error" without a package or object reference at (eval 25) line 3.
in MENTA::TemplateLoader::Instance::__ANON__ at (eval 25) line 3
in MENTA::TemplateLoader::Instance::__ANON__ at (eval 25) line 13
in MENTA::TemplateLoader::Instance::__ANON__ at (eval 25) line 23
in MENTA::TemplateLoader::__compile at lib/MENTA/TemplateLoader.pm line 31
28: include_path => [MENTA::controller_dir()],
29: package_name => 'MENTA::TemplateLoader::Instance',
30: );
31: my $out = $mtf->build_file($path)->(@params)->as_string;
32: __update_cache($path, $mtf->code);
33: return $out;
34: }
これを解決するためには「lib/MENTA/TemplateLoader.pm」を下記のように修正します。
sub __compile { my ($path, @params) = @_; MENTA::Util::require_once('Text/MicroTemplate/File.pm'); my $mtf = Text::MicroTemplate::File->new( include_path => [MENTA::controller_dir()], package_name => 'MENTA::TemplateLoader::Instance', ); #my $out = $mtf->build_file($path)->(@params)->as_string; my $out = $mtf->build_file($path)->(@_)->as_string; __update_cache($path, $mtf->code); return $out; }