extract common variables and add bse.categorize_tags()
[bse.git] / site / cgi-bin / modules / BSE / Variables.pm
CommitLineData
234312d8
TC
1package BSE::Variables;
2use strict;
3use Scalar::Util qw(blessed);
4
5our $VERSION = "1.000";
6
7sub variables {
8 my ($self, %opts) = @_;
9 my $site;
10 return
11 {
12 site => BSE::TB::Site->new,
13 url =>
14 ($opts{admin} || $opts{admin_links}
15 ? sub { $_[0]->admin }
16 : sub { $_[0]->link }
17 ),
18 admin => $opts{admin},
19 admin_links => $opts{admin_links},
20 dumper => sub {
21 require Data::Dumper;
22 return escape_html(Data::Dumper::Dumper(shift));
23 },
24 categorize_tags => \&_categorize_tags,
25 };
26}
27
28sub _categorize_tags {
29 my ($tags) = @_;
30
31 $DB::single = 1;
32 require BSE::TB::Tags;
33 my %cats;
34 for my $tag (@$tags) {
35 my $work = blessed $tag ? $tag->json_data : $tag;
36 my $cat = lc $tag->{cat};
37 unless ($cats{$cat}) {
38 $cats{$cat} =
39 {
40 name => $tag->{cat},
41 tags => [],
42 };
43 }
44 push @{$cats{$cat}{tags}}, $tag;
45 }
46
47 for my $cat (values %cats) {
48 @{$cat->{tags}} = sort { lc $a->{val} cmp lc $b->{val} } @{$cat->{tags}};
49 }
50
51 return [ sort { lc $a->{name} cmp $b->{name} } values %cats ];
52}
53
541;
55
56=head1 NAME
57
58BSE::Variables - commonly set variables
59
60=head1 SYNOPSIS
61
62 # in perl code
63 require BSE::Variables;
64 $foo->set_variable(bse => BSE::Variables->variables(%opts));
65
66 # in templates
67 <:.set level1 = bse.site.children :>
68 <:= url(article) | html :>
69 <:= tagcats = bse.categorize_tags(article.tag_objects) :>
70 <:.if bse.admin:>...
71 <:= dumper(somevar) :> lots of noise
72
73=head1 DESCRIPTION
74
75Common BSE functionality for use from the new template tags.
76
77=over
78
79=item bse.site
80
81a BSE::TB::Site object, behaves like an article in owning files and
82images, and having children.w
83
84=item bse.url(somearticle)
85
86Return the article admin link in admin (or admin_links) mode,
87otherwise the normal article link.
88
89=item bse.admin
90
91Return true in admin mode.
92
93=item bse.admin_links
94
95Return true in admin_links mode
96
97=item dumper(value)
98
99Dump the value in perl syntax using L<Data::Dumper>.
100
101=item categorize_keys(tags)
102
103Returns the given tags as a list of tag categories, each category has
104a name (of the category) and a list of tags in that category.
105
106=back
107
108=head1 AUTHOR
109
110Tony Cook <tony@develop-help.com>
111
112=cut