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?

Perl

 

sub ($c) { $c->render( template => ‘index’, date => DateTime->today ) };

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”>

x

38

 

1

#!/usr/bin/env perl

2


3

use Mojolicious::Lite -signatures;

4

use DateTime;

5


6

get '/' =>

7

    sub ($c) { $c->render( template => 'index', date => DateTime->today ) };

8


9

helper localize_date => sub ( $c, $date = DateTime->today, $style = 'full' ) {

10

    my $date_params = join ',' => $date->year, $date->month_0, $date->day;

11

    return

12

        qq<new Date($date_params).toLocaleString( [], {dateStyle: "$style"})>;

13

};

14


15

app->start;

16

__DATA__

17


18

@@ index.html.ep

19

% layout 'default';

20

% title 'Today';

21


22

<ul>

23

    <li><script>

24

        document.write(<%== localize_date $date %>)

25

    </script></li>

26

    % for my $style ( qw(long medium short) ) {

27

    <li><script>

28

        document.write(<%== localize_date $date, $style %>)

29

    </script></li>

30

    % }

31

</ul>

32


33

@@ layouts/default.html.ep

34

<!DOCTYPE html>

35

<html>

36

    <head><title><%= title %></title></head>

37

    <body><%= content %></body>

38

</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