LoginSignup
2
2

More than 5 years have passed since last update.

Text::XslateでMojolicious風のタグヘルパーを使う

Last updated at Posted at 2013-08-29

Mojolicious::Plugin::TagHelperにあるtag関数をText::Xslateで使えるようにします。
ほぼそのまま置き換えただけなので問題なく使えると思います。

test.pl
use Text::Xslate qw(html_builder html_escape);
my $tx   = Text::Xslate->new(
  function => {
      tag => sub {
          my ( $name, $attrs ) = @_;
          $attrs //= {};
          return html_builder {
              my $html = shift;
              my $tag  = "<$name";
              for my $key ( sort keys %{$attrs} ) {
                  $tag .= qq{ $key="}
                      . html_escape( $attrs->{$key} // '' ) . '"';
              }
              if ($html) {
                  $html = ref $html ? $html : html_escape($html);
                  $tag .= '>' . $html . "</$name>";
              }
              else { $tag .= ' />' }
              return $tag;
          };
      },
  },
);     

tag.tx
: my $link = 'http://yahoo.co.jp/' 
:'サンプルテキスト' | tag('a',{href=>$link});

:->{
<h1>セクションを囲む</h1>
<p>aaa</p>
:}() | tag('section');
result.html
<a href="http://yahoo.co.jp/">サンプルテキスト</a>

<section>
<h1>セクションを囲む</h1>
<p>aaa</p>
</section>

だいたいこんな感じで出力されるはずです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2