1 # -*- test-case-name: twisted.web.test.test_stan -*-
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
6 An s-expression-like syntax for expressing xml in pure python.
8 Stan tags allow you to build XML documents using Python.
10 Stan is a DOM, or Document Object Model, implemented using basic Python types
11 and functions called "flatteners". A flattener is a function that knows how to
12 turn an object of a specific type into something that is closer to an HTML
13 string. Stan differs from the W3C DOM by not being as cumbersome and heavy
14 weight. Since the object model is built using simple python types such as lists,
15 strings, and dictionaries, the API is simpler and constructing a DOM less
18 @var voidElements: the names of HTML 'U{void
19 elements<http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#void-elements>}';
20 those which can't have contents and can therefore be self-closing in the
27 Marker for markup insertion in a template.
30 @ivar name: The name of this slot. The key which must be used in
31 L{Tag.fillSlots} to fill it.
33 @type children: C{list}
34 @ivar children: The L{Tag} objects included in this L{slot}'s template.
36 @type default: anything flattenable, or C{NoneType}
37 @ivar default: The default contents of this slot, if it is left unfilled.
38 If this is C{None}, an L{UnfilledSlot} will be raised, rather than
39 C{None} actually being used.
41 @type filename: C{str} or C{NoneType}
42 @ivar filename: The name of the XML file from which this tag was parsed.
43 If it was not parsed from an XML file, C{None}.
45 @type lineNumber: C{int} or C{NoneType}
46 @ivar lineNumber: The line number on which this tag was encountered in the
47 XML file from which it was parsed. If it was not parsed from an XML
50 @type columnNumber: C{int} or C{NoneType}
51 @ivar columnNumber: The column number at which this tag was encountered in
52 the XML file from which it was parsed. If it was not parsed from an
56 def __init__(self, name, default=None, filename=None, lineNumber=None,
60 self.default = default
61 self.filename = filename
62 self.lineNumber = lineNumber
63 self.columnNumber = columnNumber
67 return "slot(%r)" % (self.name,)
73 A L{Tag} represents an XML tags with a tag name, attributes, and children.
74 A L{Tag} can be constructed using the special L{twisted.web.template.tags}
75 object, or it may be constructed directly with a tag name. L{Tag}s have a
76 special method, C{__call__}, which makes representing trees of XML natural
77 using pure python syntax.
79 @ivar tagName: The name of the represented element. For a tag like
80 C{<div></div>}, this would be C{"div"}.
83 @ivar attributes: The attributes of the element.
84 @type attributes: C{dict} mapping C{str} to renderable objects.
86 @ivar children: The child L{Tag}s of this C{Tag}.
87 @type children: C{list} of renderable objects.
89 @ivar render: The name of the render method to use for this L{Tag}. This
90 name will be looked up at render time by the
91 L{twisted.web.template.Element} doing the rendering, via
92 L{twisted.web.template.Element.lookupRenderMethod}, to determine which
96 @type filename: C{str} or C{NoneType}
97 @ivar filename: The name of the XML file from which this tag was parsed.
98 If it was not parsed from an XML file, C{None}.
100 @type lineNumber: C{int} or C{NoneType}
101 @ivar lineNumber: The line number on which this tag was encountered in the
102 XML file from which it was parsed. If it was not parsed from an XML
105 @type columnNumber: C{int} or C{NoneType}
106 @ivar columnNumber: The column number at which this tag was encountered in
107 the XML file from which it was parsed. If it was not parsed from an
110 @type slotData: C{dict} or C{NoneType}
111 @ivar slotData: The data which can fill slots. If present, a dictionary
112 mapping slot names to renderable values. The values in this dict might
113 be anything that can be present as the child of a L{Tag}; strings,
114 lists, L{Tag}s, generators, etc.
122 def __init__(self, tagName, attributes=None, children=None, render=None,
123 filename=None, lineNumber=None, columnNumber=None):
124 self.tagName = tagName
126 if attributes is None:
129 self.attributes = attributes
133 self.children = children
134 if filename is not None:
135 self.filename = filename
136 if lineNumber is not None:
137 self.lineNumber = lineNumber
138 if columnNumber is not None:
139 self.columnNumber = columnNumber
142 def fillSlots(self, **slots):
144 Remember the slots provided at this position in the DOM.
146 During the rendering of children of this node, slots with names in
147 C{slots} will be rendered as their corresponding values.
149 @return: C{self}. This enables the idiom C{return tag.fillSlots(...)} in
152 if self.slotData is None:
154 self.slotData.update(slots)
158 def __call__(self, *children, **kw):
160 Add children and change attributes on this tag.
162 This is implemented using __call__ because it then allows the natural
165 table(tr1, tr2, width="100%", height="50%", border="1")
167 Children may be other tag instances, strings, functions, or any other
168 object which has a registered flatten.
170 Attributes may be 'transparent' tag instances (so that
171 C{a(href=transparent(data="foo", render=myhrefrenderer))} works),
172 strings, functions, or any other object which has a registered
175 If the attribute is a python keyword, such as 'class', you can add an
176 underscore to the name, like 'class_'.
178 There is one special keyword argument, 'render', which will be used as
179 the name of the renderer and saved as the 'render' attribute of this
180 instance, rather than the DOM 'render' attribute in the attributes
183 self.children.extend(children)
185 for k, v in kw.iteritems():
192 self.attributes[k] = v
196 def _clone(self, obj, deep):
198 Clone an arbitrary object; used by L{Tag.clone}.
200 @param obj: an object with a clone method, a list or tuple, or something
201 which should be immutable.
203 @param deep: whether to continue cloning child objects; i.e. the
204 contents of lists, the sub-tags within a tag.
206 @return: a clone of C{obj}.
208 if hasattr(obj, 'clone'):
209 return obj.clone(deep)
210 elif isinstance(obj, (list, tuple)):
211 return [self._clone(x, deep) for x in obj]
216 def clone(self, deep=True):
218 Return a clone of this tag. If deep is True, clone all of this tag's
219 children. Otherwise, just shallow copy the children list without copying
220 the children themselves.
223 newchildren = [self._clone(x, True) for x in self.children]
225 newchildren = self.children[:]
226 newattrs = self.attributes.copy()
228 newattrs[key] = self._clone(newattrs[key], True)
232 newslotdata = self.slotData.copy()
233 for key in newslotdata:
234 newslotdata[key] = self._clone(newslotdata[key], True)
239 children=newchildren,
241 filename=self.filename,
242 lineNumber=self.lineNumber,
243 columnNumber=self.columnNumber)
244 newtag.slotData = newslotdata
251 Clear any existing children from this tag.
260 rstr += ', attributes=%r' % self.attributes
262 rstr += ', children=%r' % self.children
263 return "Tag(%r%s)" % (self.tagName, rstr)
267 voidElements = ('img', 'br', 'hr', 'base', 'meta', 'link', 'param', 'area',
268 'input', 'col', 'basefont', 'isindex', 'frame', 'command',
269 'embed', 'keygen', 'source', 'track', 'wbs')
274 A C{<![CDATA[]]>} block from a template. Given a separate representation in
275 the DOM so that they may be round-tripped through rendering without losing
278 @ivar data: The data between "C{<![CDATA[}" and "C{]]>}".
279 @type data: C{unicode}
281 def __init__(self, data):
286 return 'CDATA(%r)' % (self.data,)
290 class Comment(object):
292 A C{<!-- -->} comment from a template. Given a separate representation in
293 the DOM so that they may be round-tripped through rendering without losing
296 @ivar data: The data between "C{<!--}" and "C{-->}".
297 @type data: C{unicode}
300 def __init__(self, data):
305 return 'Comment(%r)' % (self.data,)
309 class CharRef(object):
311 A numeric character reference. Given a separate representation in the DOM
312 so that non-ASCII characters may be output as pure ASCII.
314 @ivar ordinal: The ordinal value of the unicode character to which this is
316 @type ordinal: C{int}
320 def __init__(self, ordinal):
321 self.ordinal = ordinal
325 return "CharRef(%d)" % (self.ordinal,)