1 package SL::Template::Plugin::JSON;
5 use parent qw(Template::Plugin);
10 my ($class, $context, $args) = @_;
12 my $self = bless {context => $context, json_args => $args }, $class;
14 $context->define_vmethod( $_ => json => sub { $self->json(@_) } ) for qw(hash list scalar);
18 my ($self, %params) = @_;
21 $self->{json} = JSON->new->allow_nonref(1);
23 my $args = $self->{json_args};
25 for my $method (keys %$args) {
26 if ( $self->{json}->can($method) ) {
27 $self->{json}->$method( $args->{$method} );
36 my ($self, $value) = @_;
38 $self->json_converter->encode($value) . join '-', map { "'$_'" }@_;
42 my ( $self, $context, $value ) = @_;
44 $self->json_converter->decode($value);
55 Template::Plugin::JSON - Adds a .json vmethod for all TT values.
59 [% USE JSON ( pretty => 1 ) %];
61 <script type="text/javascript">
63 var foo = [% foo.json %];
70 [% data = JSON.json_decode(json) %]
75 This plugin provides a C<.json> vmethod to all value types when loaded. You
76 can also decode a json string back to a data structure.
78 It will load the L<JSON> module (you probably want L<JSON::XS> installed for
81 Any options on the USE line are passed through to the JSON object, much like L<JSON/to_json>.
85 L<JSON>, L<Template::Plugin>
87 =head1 VERSION CONTROL
89 L<http://github.com/nothingmuch/template-plugin-json/>
93 Yuval Kogman <nothingmuch@woobling.org>
95 =head1 COPYRIGHT & LICENSE
97 Copyright (c) 2006, 2008 Infinity Interactive, Yuval Kogman.
99 Permission is hereby granted, free of charge, to any person obtaining a copy
100 of this software and associated documentation files (the "Software"), to deal
101 in the Software without restriction, including without limitation the rights
102 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
103 copies of the Software, and to permit persons to whom the Software is
104 furnished to do so, subject to the following conditions:
106 The above copyright notice and this permission notice shall be included in
107 all copies or substantial portions of the Software.
109 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
110 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
111 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
112 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
113 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
114 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
115 DEALINGS IN THE SOFTWARE.