Web::ScraperライクなテンプレートエンジンTemplate::Refine

| 0 Comments | 0 TrackBacks | このエントリーをはてなブックマークに追加 このエントリーのはてなブックマーク件数

Template::Refineというモジュールを見つけました。リンク先にある通り、ruleを使うことで簡単にテンプレートの値を置き換える事が出来ます。このモジュールの良い所は、テンプレートファイルにテンプレートエンジン専用の識別子を記述しなくて良い所。どうやって指定するかというと、XPathを使います。リンク先から引用すると

my $username = 'Test User';
my $rule = simple_replace {
    my $node = shift;
    return replace_text $node, $username;
} '//*[@class="username"]';

といった感じにルールを決め

$frag = $frag->process($rule);
say $frag->render;

と実行する事でテンプレートへの反映が行われます。まるでWeb::Scraperの様ですね。

今日はサンプルとして、美輪明宏のチンコの有無を返すAPIから得た結果をテンプレートに反映してみたいと思います。

まずテンプレート

<p>美輪明宏にチンコは...<span class="miwa">...</span>。</p>

確かにテンプレート専用の識別子は使用していません。そしてperlのコード

use strict;
use warnings;
use Encode;
use Perl6::Say;
use LWP::Simple;
use JSON;
use Template::Refine::Fragment;
use Template::Refine::Utils qw(replace_text simple_replace);

my $miwa = from_json(get "http://dzfl.jp/mojo/");
my $rule = simple_replace {
    my $node = shift;
	return replace_text $node, encode_utf8($miwa->{miwa} ? 'ある' : 'ない');
} '//*[@class="miwa"]';

my $frag = Template::Refine::Fragment->new_from_file('template.html');
print $frag->process($rule)->render;

HTMLのmiwaというクラス属性を持ったノードに対して"ある"/"ない"というテキストで置換しています。

簡単ですね。テンプレートエンジン専用の識別子を使用しないので、HTMLの属性値さえ決めておけば、テンプレートの殆どをデザイナさんに任せてしまう事も出来る様になります。

すばらしいですね。

No TrackBacks

TrackBack URL: http://perl-mongers.org/MT/mt-tb.cgi/79

Leave a comment

About this Entry

This page contains a single entry by mattn published on September 11, 2008 10:06 PM.

Getopt::Chainでgitライクなsubcommandを処理する was the previous entry in this blog.

perlはモジュール(cpan)がすてき! is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Categories

Pages

Creative Commons License
This blog is licensed under a Creative Commons License.
Powered by Movable Type 4.21-en