summaryrefslogtreecommitdiffstats
path: root/lib/Text/Handlebars.pm
blob: 63ef3981c0c2f825f1eb058f6f4b73619ea2e3d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package Text::Handlebars;
use strict;
use warnings;
# ABSTRACT: http://handlebarsjs.com/ for Text::Xslate

use Text::Xslate 1.6000;
use base 'Text::Xslate';

use Scalar::Util 'weaken';
use Try::Tiny;

=head1 SYNOPSIS

  use Text::Handlebars;

  my $handlebars = Text::Handlebars->new(
      helpers => {
          fullName => sub {
              my ($context, $person) = @_;
              return $person->{firstName}
                   . ' '
                   . $person->{lastName};
          },
      },
  );

  my $vars = {
      author   => { firstName => 'Alan', lastName => 'Johnson' },
      body     => "I Love Handlebars",
      comments => [
          author => { firstName => 'Yehuda', lastName => 'Katz' },
          body   => "Me too!",
      ],
  };

  say $handlebars->render_string(<<'TEMPLATE', $vars);
  <div class="post">
    <h1>By {{fullName author}}</h1>
    <div class="body">{{body}}</div>

    <h1>Comments</h1>

    {{#each comments}}
    <h2>By {{fullName author}}</h2>
    <div class="body">{{body}}</div>
    {{/each}}
  </div>
  TEMPLATE

produces

  <div class="post">
    <h1>By Alan Johnson</h1>
    <div class="body">I Love Handlebars</div>

    <h1>Comments</h1>

    <h2>By Yehuda Katz</h2>
    <div class="body">Me Too!</div>
  </div>

=head1 DESCRIPTION

This module subclasses L<Text::Xslate> to provide a parser for
L<Handlebars|http://handlebarsjs.com/> templates. In most ways, this module
functions identically to Text::Xslate, except that it parses Handlebars
templates instead.

Text::Handlebars accepts an additional constructor parameter of C<helpers> to
define Handlebars-style helper functions. Standard helpers are identical to
functions defined with the C<function> parameter, except that they receive the
current context implicitly as the first parameter (since perl doesn't have an
implicit C<this> parameter). Block helpers also receive the context as the
first parameter, and they also receive the C<options> parameter as a hashref.
As an example:

  sub {
      my ($context, $items, $options) = @_;

      my $out = "<ul>";

      for my $item (@$items) {
          $out .= "<li>" . $options->{fn}->($item) . "</li>";
      }

      return $out . "</ul>\n";
  },

defines a simple block helper to generate a C<< <ul> >> list.

Text::Handlebars also overrides C<render> and C<render_string> to allow using
any type of data (not just hashrefs) as a context (so rendering a template
consisting of only C<{{.}}> works properly).

=cut

sub default_helpers {
    my $class = shift;
    return {
        with => sub {
            my ($context, $new_context, $options) = @_;
            return $options->{fn}->($new_context);
        },
        each => sub {
            my ($context, $list, $options) = @_;
            return join '', map { $options->{fn}->($_) } @$list;
        },
        if => sub {
            my ($context, $conditional, $options) = @_;
            return $conditional
                ? $options->{fn}->($context)
                : $options->{inverse}->($context);
        },
        unless => sub {
            my ($context, $conditional, $options) = @_;
            return $conditional
                ? $options->{inverse}->($context)
                : $options->{fn}->($context);
        },
    };
}

sub default_functions {
    my $class = shift;
    return {
        %{ $class->SUPER::default_functions(@_) },
        %{ $class->default_helpers },
    };
}

sub options {
    my $class = shift;

    my $options = $class->SUPER::options(@_);

    $options->{compiler} = 'Text::Handlebars::Compiler';
    $options->{helpers} = {};

    return $options;
}

sub _register_builtin_methods {
    my $self = shift;
    my ($funcs) = @_;

    weaken(my $weakself = $self);
    $funcs->{'(render_string)'} = sub {
        my ($to_render, $vars) = @_;
        return $weakself->render_string($to_render, $vars);
    };
    $funcs->{'(make_block_helper)'} = sub {
        my ($code, $raw_text, $else_raw_text, $hash) = @_;

        my $options = {};
        $options->{fn} = sub {
            my ($new_vars) = @_;
            return $weakself->render_string($raw_text, $new_vars);
        };
        $options->{inverse} = sub {
            my ($new_vars) = @_;
            return $weakself->render_string($else_raw_text, $new_vars);
        };
        $options->{hash} = $hash;

        return sub { $code->(@_, $options); };
    };

    for my $helper (keys %{ $self->{helpers} }) {
        $funcs->{$helper} = $self->{helpers}{$helper};
    }
}

sub _compiler {
    my $self = shift;

    if (!ref($self->{compiler})) {
        my $compiler = $self->SUPER::_compiler(@_);
        $compiler->define_helper(keys %{ $self->{helpers} });
        $compiler->define_helper(keys %{ $self->default_helpers });
        return $compiler;
    }
    else {
        return $self->SUPER::_compiler(@_);
    }
}

sub render_string {
    my $self = shift;
    my ($string, $vars) = @_;

    if (ref($vars) && ref($vars) eq 'HASH') {
        return $self->SUPER::render_string(@_);
    }
    else {
        return $self->SUPER::render_string($string, { '.' => $vars });
    }
}

sub render {
    my $self = shift;
    my ($name, $vars) = @_;

    if (ref($vars) && ref($vars) eq 'HASH') {
        return $self->SUPER::render(@_);
    }
    else {
        return $self->SUPER::render($name, { '.' => $vars });
    }
}

=head1 BUGS/CAVEATS

=over 4

=item *

The auto-indenting behavior for partials is not yet implemented, due to
limitations in Text::Xslate.

=item *

Passing a new context to partials is not yet supported.

=item *

The C<data> parameter for C<@foo> variables when calling
C<< $options->{fn}->() >> is not supported, because I don't understand its
purpose. If someone wants this functionality, feel free to let me know, and
tell me why.

=back

Please report any bugs through RT: email
C<bug-text-handlebars at rt.cpan.org>, or browse to
L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Text-Handlebars>.

=head1 SEE ALSO

L<http://handlebarsjs.com/>

L<Text::Xslate>

=head1 SUPPORT

You can find this documentation for this module with the perldoc command.

    perldoc Text::Handlebars

You can also look for information at:

=over 4

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/Text-Handlebars>

=item * CPAN Ratings

L<http://cpanratings.perl.org/d/Text-Handlebars>

=item * RT: CPAN's request tracker

L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Text-Handlebars>

=item * Search CPAN

L<http://search.cpan.org/dist/Text-Handlebars>

=back

=for Pod::Coverage
  default_helpers
  default_functions
  options
  render
  render_string

=cut

1;