Mojolicious: prefilling an email field with a Perl expression

I am acquiring knowledge with Mojolicious templates and forms, that are obtained via Mojolicious::Plugin::TagHelpers. The problem I was facing, that I’ve reported (and solved by myself) in this forum thread, was about pre-filling an email input field with data coming from the underlying model. My first attempt was:

%= email_field 'email' => <%= $user && $user->is_logged_in ? $user->email : '' %>,  id => 'email', class => 'form-control'


where, clearly, $user is the model. This approach was wrong, since it was producing an HTML like the following:

 <input name="email" type="email" value="foo@bar.com">,  id => 'email', class => 'form-control' %>


that clearly was poorly formatted with all the extra attributes outside of the input HTML tag. The idea came to me after reasoning about the starting tag %=: this is a Perl expression line starter, and therefore everything that follows is managed as a Perl expression, as for instance the fat comma. Therefore, the right solution is to let the expressio to parse a Perl piece of code:

%= email_field 'email' => ( $user && $user->is_logged_in ? $user->email : '' ),  id => 'email', class => 'form-control'


that correctly produces the HTML that follows:

<input class="form-control" id="email" name="email" type="email" value="foo@bar.com">


The article Mojolicious: prefilling an email field with a Perl expression has been posted by Luca Ferrari on March 1, 2024