Reputation: 135
To give some context my controller selects an array ref from a query. Then the results get printed in the template like this.
home.html.ep
<td> <%= @$query_result[0]->{data} %> </td>
<td> <%= @$query_result[1]->{data} %> </td>
....
<td> <%= @$query_result[27]->{data} %> </td>
Due to some results not existing, Mojolicious throws an error ( can't use undef hash value ... )
What I am trying to do:
When Mojolicious gets to the undef hash key/value to print 'No Data'.
I have tried like this :
<td> <%= @$query_result[27]->{data} || 'no data' %> </td>
or
<td> % (exists(@$query_result[27]->{data})) ? <%= @$query_result[27]->{data} %> : 'no data' </td>
or
<td>
% if (exists($query_result[27]->{data})) {
<%= $query_result[27]->{data} %>
% } else {
'No data'
% }
I can't just remove <%= $query_result[27]->{data} %> because its returned from a query that runs on different parameters and only some parameters dont return the 27th array.
Is there a way to achieve what im trying? Thank you!
Upvotes: 1
Views: 137
Reputation: 54381
It looks like you are trying to show all the indexes from 0
to 27
, or less. You probably want to use a loop for that.
% foreach my $i ( 0 .. scalar @$query_result ) {
<td> <%= @$query_result[$i]->{data} %> </td>
% }
Now you don't have to care about the number of columns any more. Do the same for the headings and you're golden.
Alternatively, you need to check if there is something in $query_result->[27]
before you can do an exists
check, because an undef
(i.e. no value) cannot be used like a hash reference.
<td><%= $query_result->[27] ? @$query_result[27]->{data} : 'no data' </td>
Upvotes: 3