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
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>
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With