Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!

How can I use a template value like "<%= $number %>" in the Perl code inside the Mojo::Template
I am getting this error:

"Can't modify string eq in concatenation (.) or string at mytemplate.html.ep"

% foreach my $n ( @{ $data->{ names } || [] } ){ % if($n->{'year'} eq <%= $number %> ) { <tr> <td><%= $n->{'name'} %></td> <td><%= $n->{'age'} %></td> <td><%= $n->{'code'} %></td> </tr> % last; % } % }

ALso is it possible to use a sub routine from the Perl code inside the template?

The mytemplate.html.ep
% foreach my $n ( @{ $data->{ names } || [] } ){ % if($n->{'year'} eq <%= $number %> ) { <tr> <td> % name_val(<%= $n->{'name'} %>) % </td> <td><%= $n->{'age'} %></td> <td><%= $n->{'code'} %></td> </tr> % last; % } % }


The Sample code:
#!/usr/bin/env perl use strict; use warnings; use CGI; use Mojo::Template; my $q = CGI->new(); my $mt = Mojo::Template->new( vars => 1, auto_escape => 1 ); my $data; # Testing here; print $q->header( -charset => 'utf-8' ), $mt->render_file( mytemplate. +html.ep, { data => $data, number => '1', } ); sub name_val { my $name = shift || ''; # testing if($name) { return $name; }else( return "NO NAME"; ) }

Thanks a lot for looking!!

Replies are listed 'Best First'.
Re: Perl code inside the Mojo::Template
by haukex (Archbishop) on Aug 06, 2021 at 16:20 UTC

    First of all, I would very strongly recommend against using CGI.pm when you have Mojolicious available. Just use Mojo for everything! Update: I showed a code comparison between CGI.pm and Mojo in this node, and I have a bunch of Mojo examples on my scratchpad. /Update

    % if($n->{'year'} eq <%= $number %> ) {

    A line beginning with % is Perl code, and <%= $number %> is not valid Perl code. Try "% if($n->{'year'} eq $number ) {" instead.

    ALso is it possible to use a sub routine from the Perl code inside the template?

    Yes, you can use subroutines, though you usually need to import them into the template's namespace with a use statement or similar, by calling them by their full name (in your case main::name_val, though I personally find this a little ugly), you can change a template's namespace via the namespace option (though as the documentation says, be careful), or when using templates as part of a larger Mojo app, by installing them as a "helper" (see Mojolicious).

    <td> % name_val(<%= $n->{'name'} %>) % </td>

    Same problem here, try "<td><%= main::name_val( $n->{'name'} ) %></td>" instead.

      Thank you very much!
      I will work on getting rid of CGI.pm, need to get more into the way "Mojo::Template" deals with passing parameters from the Perl code to the template and vice-versa!