Dancer2: fetching nested data from hash stored in YAML session

242 views Asked by At

I'm using Dancer2 and the YAML session engine. I stored a complete hash in a session with the following code:

post '/login' => sub {
    # ...
    my $userdata = {
        fname => 'John',
        lname => 'Doe',
        uid => 1234,
    };
    # ...
    session userdata => $userdata;
    # ...
}

The omitted code checks the login data against a database and returns that $userdata hashref. This code creates a session file under $appdir/sessions with this content:

session file

userdata:
  fname: John
  lname: Doe
  uid: 1234

How can I retrieve single values from this session in my app.pm file? It works great in the template files (*.tt) and <% session.userdata.fname %> yields John, as expected. However, I want to fetch the first name in app.pm, like so:

get '/userdetails' => sub {
    my $firstname = session('userdata.fname'); # gives undef
    # do sth. with $firstname
}

Is that feasable? Or do I have to

my $userdata = session('userdata'); # fetch complete hash
# do sth. with $userdata->{fname}

I tried

  • session('userdata.fname')
  • session('userdata/fname')
  • session('userdata:fname')
  • session('userdata fname')
  • RTFM (YAML's and Dancer2's)

but none of them worked and gave undef. The manuals and tutorials only fetch "first level values", not nested ones.

1

There are 1 answers

5
Borodin On BEST ANSWER

The Template Toolkit syntax is completely independent of Perl Dancer2, and you should expect any form of addressing to carry over. The origin of the data as a YAML file is also irrelevant, as the Dancer session is just a Perl hash structure

The manual doesn't make it very clear, but

session('userdata')

is the same as

session->{userdata}

So you can use

session->{userdata}{fname}

to read the subsidiary fields

(Or possibly session('username')->{fname} if you prefer, but that looks a bit icky to me!)

Note that you shouldn't use the YAML session engine in production code, as it's very slow