root/galaxy-central/eggs/WebHelpers-0.2-py2.6.egg/webhelpers/htmlgen.py

リビジョン 3, 4.5 KB (コミッタ: kohda, 14 年 前)

Install Unix tools  http://hannonlab.cshl.edu/galaxy_unix_tools/galaxy.html

行番号 
1"""
2htmlgen
3
4Kind of like HTMLGen, only much simpler.  Like stan, only not.  The
5only important symbol that is exported is ``html``.
6
7You create tags with attribute access.  I.e., the ``A`` anchor tag is
8``html.a``.  The attributes of the HTML tag are done with keyword
9arguments.  The contents of the tag are the non-keyword arguments
10(concatenated).  You can also use the special ``c`` keyword, passing a
11list, tuple, or single tag, and it will make up the contents (this is
12useful because keywords have to come after all non-keyword arguments,
13which is non-intuitive).
14
15If the value of an attribute is None, then no attribute will be
16inserted.  So::
17
18    >>> html.a(href='http://www.yahoo.com', name=None, c='Click Here')
19    '<a href=\"http://www.yahoo.com\">Click Here</a>'
20
21If a non-string is passed in, then ``webhelpers.escapes.html_escape``
22is called on the value.
23
24``html`` can also be called, and it will concatenate the string
25representations of its arguments.
26
27``html.comment`` will generate an HTML comment, like
28``html.comment('comment text', 'and some more text')`` -- note that it
29cannot take keyword arguments (because they wouldn't mean anything).
30
31For cases where you cannot use a name (e.g., for the ``class``
32attribute) you can append an underscore to the name, like
33``html.span(class_='alert')``.
34
35Examples::
36
37    >>> print html.html(
38    ...    html.head(html.title(\"Page Title\")),
39    ...    html.body(
40    ...    bgcolor='#000066',
41    ...    text='#ffffff',
42    ...    c=[html.h1('Page Title'),
43    ...       html.p('Hello world!')],
44    ...    ))
45    <html>
46    <head>
47    <title>Page Title</title>
48    </head>
49    <body text=\"#ffffff\" bgcolor=\"#000066\">
50    <h1>Page Title</h1><p>
51    Hello world!
52    </p>
53    </body>
54    </html>
55    >>> html.a(href='#top', c='return to top')
56    '<a href=\"#top\">return to top</a>'
57    >>> 1.4
58    1.4
59
60.. note::
61
62   Should this return objects instead of strings?  That would allow
63   things like ``html.a(href='foo')('title')``.  Also, the objects
64   could have a method that shows that they are trully HTML, and thus
65   should not be further quoted.
66
67   However, in some contexts you can't use objects, you need actual
68   strings.  But maybe we can just make sure those contexts don't
69   happen in webhelpers.
70"""
71
72from util import html_escape
73
74__all__ = ['html']
75
76def strify(s):
77    if s is None:
78        return ''
79    if not isinstance(s, basestring):
80        s = unicode(s)
81    if isinstance(s, unicode):
82        s = s.encode('ascii', 'xmlcharrefreplace')
83    return s
84
85class UnfinishedComment:
86
87    def __call__(self, *args):
88        return '<!--%s-->' % '\n'.join(map(strify, args))
89
90class Base:
91
92    comment = UnfinishedComment()
93
94    def __getattr__(self, attr):
95        if attr.startswith('__'):
96            raise AttributeError
97        attr = attr.lower()
98        return UnfinishedTag(attr)
99
100    def __call__(self, *args):
101        return ''.join(map(str, args))
102
103    def escape(self, *args):
104        return ''.join(map(html_escape, args))
105
106    def str(self, arg):
107        return strify(arg)
108
109class UnfinishedTag:
110
111    def __init__(self, tag):
112        self._tag = tag
113
114    def __call__(self, *args, **kw):
115        return tag(self._tag, *args, **kw)
116
117    def __str__(self):
118        if self._tag in empty_tags:
119            return '<%s />' % self._tag
120        else:
121            return '<%s></%s>' % (self._tag, self._tag)
122
123def tag(tag, *args, **kw):
124    if kw.has_key("c"):
125        if args:
126            raise TypeError(
127                "The special 'c' keyword argument cannot be used in "
128                "conjunction with non-keyword arguments")
129        args = kw["c"]
130        del kw["c"]
131    attrargs = []
132    for attr, value in kw.items():
133        if value is None:
134            continue
135        if attr.endswith('_'):
136            attr = attr[:-1]
137        attrargs.append(' %s="%s"' % (attr, html_escape(value)))
138    if not args and tag in empty_tags:
139        return '<%s%s />' % (tag, ''.join(attrargs))
140    else:
141        return '<%s%s>%s</%s>' % (
142            tag, ''.join(attrargs), ''.join(map(strify, args)),
143            tag)
144
145# Taken from: http://www.w3.org/TR/REC-html40/index/elements.html
146empty_tags = {}
147for _t in ("area base basefont br col frame hr img input isindex "
148           "link meta param".split()):
149    empty_tags[_t] = None
150
151block_level_tags = {}
152for _t in ("applet blockquote body br dd div dl dt fieldset "
153           "form frameset head hr html iframe map menu noframes "
154           "noscript object ol optgroup p param script select "
155           "table tbody tfoot thead tr ul var"):
156    block_level_tags[_t] = None
157
158html = Base()
159
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。