From c4fd3dc97042a13cf365f06dd84bb6b02a1efdfb Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Thu, 4 Oct 2012 16:06:38 -0500 Subject: implement helpers --- lib/Text/Handlebars.pm | 16 ++++++++++++++++ lib/Text/Xslate/Syntax/Handlebars.pm | 12 ++++++++++-- t/helpers.t | 4 +--- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/lib/Text/Handlebars.pm b/lib/Text/Handlebars.pm index 7c975b9..fd3fc28 100644 --- a/lib/Text/Handlebars.pm +++ b/lib/Text/Handlebars.pm @@ -63,7 +63,10 @@ sub options { my $class = shift; my $options = $class->SUPER::options(@_); + $options->{compiler} = 'Text::Handlebars::Compiler'; + $options->{helpers} = {}; + return $options; } @@ -86,6 +89,19 @@ sub _register_builtin_methods { return 1 if try { $weakself->find_file($filename); 1 }; return 0; }; + + for my $helper (keys %{ $self->{helpers} }) { + my $code = $self->{helpers}{$helper}; + $funcs->{$helper} = sub { + my ($raw_text, @args) = @_; + my $recurse = sub { + my ($vars) = @_; + return $weakself->render_string($raw_text, $vars); + }; + + return $code->(@args, { fn => $recurse }); + } + } } 1; diff --git a/lib/Text/Xslate/Syntax/Handlebars.pm b/lib/Text/Xslate/Syntax/Handlebars.pm index ef0ee9c..63b93b6 100644 --- a/lib/Text/Xslate/Syntax/Handlebars.pm +++ b/lib/Text/Xslate/Syntax/Handlebars.pm @@ -311,7 +311,7 @@ sub std_block { $name = $name->third; } - if ($name->arity ne 'variable' && $name->arity ne 'field') { + if ($name->arity ne 'variable' && $name->arity ne 'field' && $name->arity ne 'call') { $self->_unexpected("opening block name", $self->token); } $self->advance(';'); @@ -332,7 +332,7 @@ sub std_block { $closing_name = $closing_name->third; } - if ($closing_name->arity ne 'variable' && $closing_name->arity ne 'field') { + if ($closing_name->arity ne 'variable' && $closing_name->arity ne 'field' && $closing_name->arity ne 'call') { $self->_unexpected("closing block name", $self->token); } if ($closing_name->id ne $name->id) { # XXX @@ -341,6 +341,14 @@ sub std_block { $self->advance(';'); + if ($name->arity eq 'call') { + unshift @{ $name->second }, ( + $raw_text->clone, + $self->symbol('(vars)')->clone(arity => 'vars'), + ); + return $self->print_raw($name); + } + my $iterations = $inverted ? ($self->make_ternary( $self->call('(is_array)', $name->clone), diff --git a/t/helpers.t b/t/helpers.t index ad601e9..439f191 100644 --- a/t/helpers.t +++ b/t/helpers.t @@ -5,7 +5,6 @@ use lib 't/lib'; use Test::More; use Test::Handlebars; -{ local $TODO = "unimplemented"; local $SIG{__WARN__} = sub { }; render_ok( { helpers => { @@ -25,7 +24,7 @@ render_ok( { helpers => { list => sub { - my ($items, $options) = @_; + my ($context, $items, $options) = @_; my $out = "