DZone
Last week’s article received a comment on a private Facebook group that amounted to “just use JavaScript’s built-in formatting.” So what would that look like?
helper localize_date => sub ( $c, $date = DateTime->today, $style = ‘full’ ) {
my $date_params = join ‘,’ => $date->year, $date->month_0, $date->day;
return
qq;
};
app->start;
__DATA__
@@ index.html.ep
% layout ‘default’;
% title ‘Today’;
% for my $style ( qw(long medium short) ) {
% }
@@ layouts/default.html.ep
” data-lang=”text/x-perl”>
#!/usr/bin/env perl
use :: - ;
use ;
'/' =>
sub ($c) { $c-> ( => 'index', => -> ) };
=> sub ( $c, $date = -> , $style = 'full' ) {
my $date_params = join ',' => $date-> , $date-> , $date-> ;
return
qq<new Date($date_params).toLocaleString( [], {dateStyle: "$style"})>;
};
-> ;
__DATA__
@@ index.html.ep
% layout 'default';
% title 'Today';
<ul>
<li><script>
document.write(<%== localize_date $date %>)
</script></li>
% for my $style ( qw(long medium short) ) {
<li><script>
document.write(<%== localize_date $date, $style %>)
</script></li>
% }
</ul>
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
It’s structured much like the Perl-only solution, with a default "/"
route and a localize_date
Mojolicious helper to do the formatting. I opted to output a piece of JavaScript from the helper on lines 11 through 14 since it could be repeated several times in a document. You could instead declare a function in the default layout’s HTML <head>
on line 38 that would receive a date and a formatting style, outputting the resulting formatted date.
Source: DZone