Dancer でTemplate-Toolkitを使うときにハマったことメモ
Dancer でWebアプリを作っているのだけど、ViewにTemplate-Toolkitを使うとplackupしてもデバッグメッセージが出てきてしまうという罠。
ドキュメントやソースを読んだ末に、以下方法で解決できたっぽいのでメモしておきます。
Dancer/Template/TemplateToolkit.pm を修正
use Encode; # 上のほうで sub render($$$) { my ($self, $template, $tokens) = @_; die "'$template' is not a regular file" if !ref($template) && (!-f $template); my $content = ""; $_engine->process($template, $tokens, \$content) or die $_engine->error; - return $content; + return Encode::encode('utf-8', $content); }
config.yml を以下のように設定
engines: template_toolkit: UNICODE: 1 ENCODING: "utf-8"
アプリでのパラメータ指定
get '/' => sub { template 'index', {}, { layout => 0 }; };
template の第2引数に { layout => 0 } を入れる。
いちいち各所で指定しないといけないのが面倒であり難点。
Dancer/Helpers.pm の template() がそのあたりの処理を司っているので、そこを変えればデフォルト値を変えることができそう(自分はやってない)。
sub template { my ($view, $tokens, $options) = @_; $options ||= {layout => 1}; my $layout = setting('layout'); undef $layout unless $options->{layout}; # ...
本家コードはgithubにあるので、forkとかすればいいのかな。しかしまだgit理解できてない罠なので後でやろう。
参考
use Encode; - 今日のCPANモジュール http://e8y.net/mag/015-encode/