Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert perl hash to javascript hash

I am working in template toolkit framework. I have got an perl hash datatype in my tt file. I want to convert this hash datatype to javascript hash datatype.

code: template:

        [% PERL %]
        use JSON qw(encode_json);

        my $vars = {

            'version'  => 3.14,
            'days'     => [ qw( mon tue wed thu fri sat sun ) ],
            'cgi'      => CGI->new(),
            'me'       => {
                'id'     => 'abw',
                'name'   => 'Andy Wardley',
            },
        };

        my $json = encode_json($vars->{'me'});
    [% END %]


 <script>
   function callme(){
   var me = [% $json %]
  }
</script>

now i want the me hash to be accessible in javascript

like image 929
Kalai Avatar asked Nov 23 '12 12:11

Kalai


2 Answers

There are several TT plugins available to do this, any of which would be a better solution than embedding raw perl into your template. Personally, I prefer JSON::Escape, but there are a few others. In more than 5 years of writing TT on a more or less daily basis, I've never yet had to resort to using the [% PERL %] directive. I'm not writing CGI though, I suppose. YMMV.

[%- USE JSON.Escape( pretty => 1 );
    SET me = { id => 'abw', name => 'Andy Wardley' };
...
-%]

<script>
    function callme() {
    var me = [% me.json %]
    ...
</script>
like image 74
RET Avatar answered Sep 21 '22 17:09

RET


Try using JSON from CPAN. It's JavaScript Simple Object Notation and you directly use it in JavaScript.

use JSON qw(encode_json);

my $vars = {

    'version'  => 3.14,
    'days'     => [ qw( mon tue wed thu fri sat sun ) ],
    'cgi'      => CGI->new(),
    'me'       => {
        'id'     => 'abw',
        'name'   => 'Andy Wardley',
    },
};
print encode_json($vars->{'me'});

Output:

{"name":"Andy Wardley","id":"abw}
like image 31
simbabque Avatar answered Sep 22 '22 17:09

simbabque