Debian Codegraph @

lib/HTML/FormHandler/Render/Util.pm

raw
1 package HTML::FormHandler::Render::Util;
2 # ABSTRACT: rendering utility
3 $HTML::FormHandler::Render::Util::VERSION = '0.410002';
4 use strict;
5 use warnings;
6 use Sub::Exporter;
7 Sub::Exporter::setup_exporter({ exports => [ 'process_attrs', 'cc_widget', 'ucc_widget' ] } );
8 use HTML::Entities qw( encode_entities );
9
10
11 # this is a function for processing various attribute flavors
12 sub process_attrs {
13 my ($attrs) = @_;
14
15 my @use_attrs;
16 my $javascript = delete $attrs->{javascript} || '';
17 for my $attr( sort keys %$attrs ) {
18 my $value = '';
19 if( defined $attrs->{$attr} ) {
20 if( ref $attrs->{$attr} eq 'ARRAY' ) {
21 # we don't want class="" if no classes specified
22 next unless scalar @{$attrs->{$attr}};
23 $value = join (' ', @{$attrs->{$attr}} );
24 }
25 else {
26 $value = $attrs->{$attr};
27 }
28 }
29 # we use double quotes as the delimiter so only html encode those
30 # HTML attribute context
31 # as we use double quotes we need to encode those
32 # & is the html encoding character and therefore needs encoding as well
33 push @use_attrs, sprintf( '%s="%s"', $attr, encode_entities($value, '"&') );
34 }
35 my $output = join( ' ', @use_attrs );
36 $output = " $output" if length $output;
37 $output .= " $javascript" if $javascript;
38 return $output;
39 }
40
41 sub cc_widget {
42 my $widget = shift;
43 return '' unless $widget;
44 if($widget eq lc $widget) {
45 $widget =~ s/^(\w{1})/\u$1/g;
46 $widget =~ s/_(\w{1})/\u$1/g;
47 }
48 return $widget;
49 }
50
51 sub ucc_widget {
52 my $widget = shift;
53 if($widget ne lc $widget) {
54 $widget =~ s/::/_/g;
55 $widget = ucfirst($widget);
56 my @parts = $widget =~ /([A-Z][a-z]*)/g;
57 $widget = join('_', @parts);
58 $widget = lc($widget);
59 }
60 return $widget;
61 }
62
63
64 1;
65
66 __END__
67
68 =pod
69
70 =encoding UTF-8
71
72 =head1 NAME
73
74 HTML::FormHandler::Render::Util - rendering utility
75
76 =head1 VERSION
77
78 version 0.410002
79
80 =head1 SYNOPSIS
81
82 The 'process_attrs' takes a hashref and creates an attribute string
83 for constructing HTML.
84
85 my $attrs => {
86 some_attr => 1,
87 placeholder => 'Enter email...",
88 class => ['help', 'special'],
89 };
90 my $string = process_attrs($attrs);
91
92 ...will produce:
93
94 ' some_attr="1" placeholder="Enter email..." class="help special"'
95
96 If an arrayref is empty, it will be skipped. For a hash key of 'javascript'
97 only the value will be appended (without '$key=""');
98
99 =head1 AUTHOR
100
101 FormHandler Contributors - see HTML::FormHandler
102
103 =head1 COPYRIGHT AND LICENSE
104
105 This software is copyright (c) 2017 by Gerda Shank.
106
107 This is free software; you can redistribute it and/or modify it under
108 the same terms as the Perl 5 programming language system itself.
109
110 =cut