¶ zqcategories.py

2011-08-31 23:22

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4
"""
- 仅仅要求可以根据指定顺序输出分类目录
 
Walks through your blog root figuring out all the categories you have
and how many entries are in each category.  It generates html with
this information and stores it in the $categorylinks variable which
you can use in your head or foot templates.
 
You can format the output by setting "category_begin", "category_item",
"category_end" and properties.
 
Categories exist in a hierarchy.  "category_start" starts the category listing
and is only used at the very beginning.  The "category_begin" property begins a
new category group and the "category_end" property ends that category group. 
The "category_item" property is the template for each category item.  Then
after all the categories are printed, "category_finish" ends the category
listing.
 
For example, the following properties will use <ul> to open a category, </ul>
to close a category and <li> for each item:
 
py["category_start"] = "<ul>"
py["category_begin"] = "<li><ul>"
py["category_item"] = r'<li><a href="%(base_url)s/%(category_urlencoded)sindex">%(category)s</a></li>'
py["category_end"] = "</ul>"
py["category_finish"] = "</li></ul>"
 
 
Another example, the following properties don't have a begin or an end but
instead use indentation for links and displays the number of entries in that
category:
 
py["category_start"] = ""
py["category_begin"] = ""
py["category_item"] = r'%(indent)s<a href="%(base_url)s/%(category_urlencoded)sindex">%(category)s</a> (%(count)d)<br>'
py["category_end"] = ""
py["category_finish"] = ""
 
There are no variables available in the category_begin or category_end
templates.
 
Available variables in the category_item template:
 
  variable                 example                      datatype
  ========                 =======                      ========
  base_url                 http://joe.com/blog/         string
  fullcategory_urlencoded  'dev/pyblosxom/status/'      string
  fullcategory             'dev/pyblosxom/status/'      string (urlencoded)
  category                 'status/'                    string
  category_urlencoded      'status/'                    string (urlencoed)
  flavour                  'html'                       string
  count                    70                           int
  indent                   '    '   string
 
 
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 
Copyright 2004, 2005, 2006 Will Guaraldi
"""
__author__ = "Will Guaraldi - willg at bluesock dot org"
__version__ = "$Id: zqcategories.py,v 2872b22e2ace 2011/10/27 07:08:25 zoomquiet+hg $"
__description__ = "Builds a list of categories."
 
from Pyblosxom import tools
import re, os
 
DEFAULT_START = r'<ul class="categorygroup">'
DEFAULT_BEGIN = r'<li><ul class="categorygroup">'
DEFAULT_ITEM = r'<li><a href="%(base_url)s/%(fullcategory_urlencoded)sindex.%(flavour)s">%(category)s</a> (%(count)d)</li>'
DEFAULT_END = "</ul></li>"
DEFAULT_FINISH = "</ul>"
DEFAULT_ROOT = []
 
def verify_installation(request):
    config = request.getConfiguration()
    if not config.has_key("category_template"):
        print "missing optional config property 'category_template' which allows "
        print "you to specify how the category hierarchy is rendered.  see"
        print "the documentation at the top of the pycategories plugin code "
        print "file for more details."
    return 1
 
class PyblCategories:
    def __init__(self, request):
        self._request = request
        self._categories = None
        config = self._request.getConfiguration()
        self._baseurl = config.get("base_url", "")
 
        self.genCategories()
 
 
    def __str__(self):
        if self._categories == None:
            self.genCategories()
        return self._categories
 
    def genCategories(self):
        config = self._request.getConfiguration()
        root = config["datadir"]
 
        start_t = config.get("category_start", DEFAULT_START)
        begin_t = config.get("category_begin", DEFAULT_BEGIN)
        item_t = config.get("category_item", DEFAULT_ITEM)
        end_t = config.get("category_end", DEFAULT_END)
        finish_t = config.get("category_finish", DEFAULT_FINISH)
        #zoomq: configed order by mind the catrgorise
        root_path_list = config.get("category_root_list", DEFAULT_ROOT)
 
        cfgBaseUrl = config.get("base_url", "")
 
        form = self._request.getForm()
        flavour = (form.has_key('flav') and form['flav'].value or
            config.get('default_flavour', 'html'))
        #print flavour
 
        # build the list of all entries in the datadir
        output = ""
        #@others
        if 0==len(root_path_list):  #as default walk and export Categories as word order
            elist = tools.Walk(self._request, root)
            output += self._subCategories(elist,root,"")
        else:
            for rootCategory in root_path_list:
                subroot = "%s/%s"%(root,rootCategory)
                self._baseurl = "%s/%s"%(cfgBaseUrl,rootCategory)
                elist = tools.Walk(self._request, subroot)
                output += self._subCategories(elist,subroot,rootCategory)
 
        # then we join the list and that's the final string
        #self._categories = "\n".join(output)
        self._categories = output
 
    def _subCategories(self,elist,root,rootname):
        config = self._request.getConfiguration()
        form = self._request.getForm()
        flavour = (form.has_key('flav') and form['flav'].value or
            config.get('default_flavour', 'html'))
        start_t = config.get("category_start", DEFAULT_START)
        begin_t = config.get("category_begin", DEFAULT_BEGIN)
        item_t = config.get("category_item", DEFAULT_ITEM)
        end_t = config.get("category_end", DEFAULT_END)
        finish_t = config.get("category_finish", DEFAULT_FINISH)
 
        # peel off the root dir from the list of entries
        elist = [mem[len(root)+1:] for mem in elist]
 
        # go through the list of entries and build a map that
        # maintains a count of how many entries are in each
        # category
        elistmap = {}
        for mem in elist:
            mem = os.path.dirname(mem)
            elistmap[mem] = 1 + elistmap.get(mem, 0)
        self._elistmap = elistmap
        #print self._elistmap
        # go through the elistmap keys (which is the list of
        # categories) and for each piece in the key (i.e. the key
        # could be "dev/pyblosxom/releases" and the pieces would
        # be "dev", "pyblosxom", and "releases") we build keys
        # for the category list map (i.e. "dev", "dev/pyblosxom",
        # "dev/pyblosxom/releases")
        clistmap = {}
        for mem in elistmap.keys():
            mem = mem.split(os.sep)
            for index in range(len(mem)+1):
                p = os.sep.join(mem[0:index])
                clistmap[p] = 0
 
        # then we take the category list from the clistmap and
        # sort it alphabetically
        clist = clistmap.keys()
        clist.sort()
 
        output = []
        indent = 0
 
        output.append(start_t)
        # then we generate each item in the list
        for item in clist:
            itemlist = item.split(os.sep)
 
            num = 0
            for key in self._elistmap.keys():
                if item == '' or key == item or key.startswith(item + os.sep):
                    num = num + self._elistmap[key]
 
            if not item:
                tab = ""
            else:
                tab = len(itemlist) * "  "
 
            if indent > len(itemlist):
                for i in range(indent - len(itemlist)):
                    output.append(end_t)
 
            elif indent < len(itemlist):
                for i in range(len(itemlist) - indent):
                    output.append(begin_t)
 
            # now we build the dict with the values for substitution
            d = { "base_url":     self._baseurl,
                  "fullcategory": item + "/",
                  "category":     itemlist[-1] + "/",
                  "flavour":      flavour,
                  "count":        num,
                  "indent":       tab }
 
            # this prevents a double / in the root category url
            if item == "":
                d["fullcategory"] = item
            #print d
            # this adds urlencoded versions
            d["fullcategory_urlencoded"] = tools.urlencode_text(d["fullcategory"])
            d["category_urlencoded"] = tools.urlencode_text(d["category"])
 
            # and we toss it in the thing
            output.append(item_t % d)
 
            indent = len(itemlist)
 
        output.append(end_t * indent)
        output.append(finish_t)
        # export define item's name
        output[2] = output[2].replace(">/"," class='rootcategory'>%s/"%rootname)
        return "\n".join(output)
def cb_prepare(args):
    request = args["request"]
    data = request.getData()
    data["categorylinks"] = PyblCategories(request)
 
</li>

§ 写于: Wed, 31 Aug 2011 | 永久链接;源文: rdf ,rss ,raw | 分类: /techic/PyBlosxom/plugins §
[MailMe] [Print] Creative Commons License

作品Zoom.Quiet创作,采用知识共享署名-相同方式共享 2.5 中国大陆许可协议进行许可。 基于zoomquiet.org上的作品创作。