kivitendo/SL/Template/Plugin/JSON.pm @ 58cc1c78
7fa5f43b | Sven Schöling | package SL::Template::Plugin::JSON;
|
||
d259fd66 | Sven Schöling | use strict;
|
||
7fa5f43b | Sven Schöling | use JSON ();
|
||
use Carp qw(croak);
|
||||
b27c05d6 | Sven Schöling | use base qw(Template::Plugin);
|
||
7fa5f43b | Sven Schöling | |||
our $VERSION = "0.06";
|
||||
sub new {
|
||||
my ($class, $context, $args) = @_;
|
||||
my $self = bless {context => $context, json_args => $args }, $class;
|
||||
b27c05d6 | Sven Schöling | $context->define_vmethod($_, json => sub { $self->json(@_) }) for qw(hash list scalar);
|
||
return $self;
|
||||
7fa5f43b | Sven Schöling | }
|
||
sub json_converter {
|
||||
my ($self, %params) = @_;
|
||||
if (!$self->{json}) {
|
||||
7647d46a | Moritz Bunkus | $self->{json} = JSON->new->allow_nonref(1)->convert_blessed(1);
|
||
7fa5f43b | Sven Schöling | |||
my $args = $self->{json_args};
|
||||
for my $method (keys %$args) {
|
||||
if ( $self->{json}->can($method) ) {
|
||||
$self->{json}->$method( $args->{$method} );
|
||||
}
|
||||
}
|
||||
}
|
||||
return $self->{json};
|
||||
}
|
||||
sub json {
|
||||
my ($self, $value) = @_;
|
||||
b27c05d6 | Sven Schöling | $self->json_converter->encode($value);
|
||
7fa5f43b | Sven Schöling | }
|
||
sub json_decode {
|
||||
b27c05d6 | Sven Schöling | my ( $self, $value ) = @_;
|
||
7fa5f43b | Sven Schöling | |||
$self->json_converter->decode($value);
|
||||
}
|
||||
1;
|
||||
__END__
|