Converting a Perl hash into a JavaScript hash: A comprehensive guide

I am currently using the template toolkit framework and working with a Perl hash data type in my tt file. My goal is to convert this Perl hash data type into a JavaScript hash data type.

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 need to make sure that the "me" hash is accessible in JavaScript.

Answer №1

If you're looking to avoid embedding raw Perl into your template, there are numerous TT plugins at your disposal that offer better solutions. Personally, I find JSON::Escape to be my preferred choice, although there are other options available as well. After more than half a decade of working with TT on a regular basis, I have yet to rely on the [% PERL %] directive. It's worth noting that my work does not involve CGI scripting, so your mileage may vary.

[%- USE JSON.Escape( pretty => 1 );
    SET me = { id => 'abc', name => 'Alice Brown' };
...
-%]

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

Answer №2

Consider utilizing the JSON module from CPAN. It is based on JavaScript Simple Object Notation, allowing for direct usage 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'});

Expected Output:

{"name":"Andy Wardley","id":"abw}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for invoking the href function in jwplayer with individual arguments

I need assistance with configuring jwplayer to load a list of href links one by one. Each href link includes a function that needs to be triggered automatically with specific parameters passed to JavaScript. Below is the code snippet I am currently worki ...

Application unable to save data to file with no indication in error logs

Recently, I've been experimenting with the Capture-Website package, which is designed to save website screenshots to a file. Initially, everything was working smoothly until I decided to restart the server. Now, although my code is running without a ...

Enhancing the camera functionality of the HTML <input> tag for iPhone and Android devices

I am currently working on a mobile web application that requires access to the device's camera. I am aware that this can be achieved using the following code: <input type="file" accept="image/*" capture="camera" /> The code snippet above suc ...

Rearranging div placement based on the width of the screen

I am currently working on building a responsive website and I need two divs to switch positions depending on the screen width, both on initial load and when resizing. Despite my efforts in researching and trying various options, I have not been successful ...

I have come across this building error, what do you think is the cause of it?

My attempt to launch my company's React.js project, downloaded from Tortoise SVN, is encountering an issue. PS C:\Projects\Old EHR> yarn start yarn run v1.22.19 $ next start ready - started server on 0.0.0.0:3000, url: http://localhost:30 ...

The issue with importing data into Google Sheets due to an error with Ljava

After combining different scripts, I am struggling to properly input data into the code. Email Input: *Status:* *Date:* 03/31/2020 *WorkOrder:* 123456-1 *DMSShipDate:* 03/31/2020 *PONumber:* 8675309 *Company:* Test New Script var ui = SpreadsheetApp.g ...

Utilizing Jquery Validation to Remove a Class Upon Form Validation Success

In my current registration process, I have a multipart form where each subsequent form is displayed when the next button is pressed without fading effects. Initially, the button appears faded. Here's a simplified version of how I handle the first form ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

Load/run JavaScript code before sending email blade template

Is it feasible to embed and run JavaScript code in a blade template before sending an email? The challenge lies in sending users some dynamically generated images from a third-party program requested via AJAX. The current setup is as follows: //report. ...

No action is triggered after submitting AJAX data in a WordPress environment

I'm currently working on developing a WordPress plugin that requires querying the database. However, I am facing challenges in getting it to function properly. Here is the code snippet that I have attempted: jQuery('#demo_ajax').submit(func ...

Load HTML table values dynamically with Ajax post page load in PHP

My goal is to retrieve the connectivity status of available servers in a database on a PHP page. <tbody> <?php foreach ($data['servers'] as $server) { ?> <tr> <td class=""><?php echo $server->server_ ...

Adjust the height of the Accordion component in Material UI

I am currently in the process of migrating a JavaFx HMI to a web application that utilizes React.js. To display graphical widgets, I am also working with Material.ui. In order to maintain consistency with the original HMI layout, I need to adjust the layo ...

Resize a div within another div using overflow scroll and centering techniques

Currently, I am working on implementing a small feature but am facing difficulties with the scroll functionality. My goal is to zoom in on a specific div by scaling it using CSS: transform: scale(X,Y) The issue I am encountering lies in determining the c ...

Transform uploaded image file into a blob format and store it in a VueJS database

I am facing an issue with my form that has multiple inputs, including one of type "file". My goal is to upload an image and then submit the form to the API for storage in the database. <input name="image" class="w-full border-2 border-gray-200 rounded-3 ...

Having trouble logging JSON data from nodejs + express while serving static files through express. However, I am able to see the data when I only make a GET request for the JSON data without the static files

Currently, I am experimenting with sending data from a nodejs + express server to the front-end static files. The objective is for JavaScript (allScripts.js) on the front-end to process this data. At this stage, my aim is to log the data to the console to ...

Develop a sophisticated multi-page application using create-react-app in conjunction with express.js

While I'm comfortable with back-end work, my front-end programming skills have gotten rusty. I used to work a lot with React, but it's been over a year since I last touched it. Recently, I started a project that requires me to refresh my knowledg ...

Tips for managing the sub query in nodejs?

Developed a RESTful API in nodeJS focusing on a Post-type feature. The process involves executing two queries: 1. Initially fetching user-Id and answer details from the answers table. Upon checking the console, two user-Ids are displayed. 2. Secondly, que ...

How can we align the top edge of a div to the center of a circle within a separate div in a responsive manner?

I want to create 2 stacked divs: the first div contains a circular image, and the second div contains text. I want the second div to always cover half of the circle, with its upper edge positioned at the center point of the circle. This is my code: .cov ...

Rails 5 not allow user submission of bootstrap modal form

I am facing an issue with a form inside a modal in my Rails application. When I click on the submit button, nothing happens. How can I use Ajax to submit the modal form and save its content on another page? <button type="button" class="btn btn-primary ...

Tips to store Google fonts in the assets directory

I've included this link in my styles.scss @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap'); While it works locally, the API fails on production or is blocked. How can I host it within my p ...