def render(self, data): r = [] i = 0 notpresent = T.td(_class="notpresent")[T.acronym( title="Unable to get IP from ARP tables")["N/A"]] for row in data: mac = T.td[T.span(data=row[0], render=T.directive("mac"))] if row[1] is not None: r.append( T.tr(_class=(i % 2) and "odd" or "even") [mac, T.td[T.invisible(data=row[1], render=T.directive("ip"))]]) else: r.append( T.tr(_class=(i % 2) and "odd" or "even")[mac, notpresent]) i += 1 if len(r) == 1: return [('FDB', [ T.span(data=data[0][0], render=T.directive("mac")), data[0][1] and [", ", T.span(data=data[0][1], render=T.directive("ip"))] or "" ], 1)] return [('FDB', [ len(r) == 20 and "20+" or len(r), T.span(render=T.directive("tooltip"), data=T.table(_class="mac")[T.thead[T.td["MAC"], T.td["IP"]], r]) ], len(r) == 20 and 21 or len(r))]
def render(self, data): r = [] i = 0 vlanlist = [] notpresent = T.td(_class="notpresent")[T.acronym( title="Not present or no information from remote")["N/A"]] for row in data: if row[1] is not None: vlanlist.append(str(row[0])) vid = T.td[T.span(data=row[0], render=T.directive("vlan"))] if row[1] is None: r.append( T.tr(_class=(i % 2) and "odd" or "even")[vid, notpresent, T.td[row[2]]]) elif row[2] is None: r.append( T.tr(_class=(i % 2) and "odd" or "even")[vid, T.td[row[1]], notpresent]) elif row[1] == row[2]: r.append( T.tr(_class=(i % 2) and "odd" or "even")[ vid, T.td(colspan=2)[row[1]]]) else: r.append( T.tr(_class=(i % 2) and "odd" or "even")[vid, T.td[row[1]], T.td[row[2]]]) i += 1 vlantable = T.table(_class="vlan")[T.thead[T.td["VID"], T.td["Local"], T.td["Remote"]], r] return [('VLAN', [[[T.span(data=v, render=T.directive("vlan")), " "] for v in vlanlist], T.span(render=T.directive("tooltip"), data=vlantable)], ", ".join(vlanlist))]
def render(self, data): r = [] i = 0 notpresent = T.td(_class="notpresent")[ T.acronym(title="Unable to get IP from ARP tables")["N/A"]] for row in data: mac = T.td[T.span(data=row[0], render=T.directive("mac"))] if row[1] is not None: r.append(T.tr(_class=(i%2) and "odd" or "even") [mac, T.td[T.invisible(data=row[1], render=T.directive("ip"))]]) else: r.append(T.tr(_class=(i%2) and "odd" or "even") [mac, notpresent]) i += 1 if len(r) == 1: return [('FDB', [T.span(data=data[0][0], render=T.directive("mac")), data[0][1] and [", ", T.span(data=data[0][1], render=T.directive("ip"))] or ""], 1)] return [('FDB', [len(r) == 20 and "20+" or len(r), T.span(render=T.directive("tooltip"), data=T.table(_class="mac")[ T.thead[T.td["MAC"], T.td["IP"]], r])], len(r) == 20 and 21 or len(r))]
def render_userbox(self, ctx, data): """Render the box containing the user's login status.""" avatar = maybe_user(ctx) srv = IService(ctx) warn = '' if avatar.anonymous: email = None else: email = avatar.user.email if not email: email = srv.pretendedEmail(avatar.user) warn = T.span( id="activate")[u"Vous devez encore ", T.a(href="/")[u"activer votre compte"]] if email: greetings = T.div( _class="userinfo")[warn, T.span(style="padding-right:3em")[email], T.a(href="/")[u"Réservations"], u' :: ', T.a(href="/logout")[u"Quitter"], ] else: info = login.LoginInfo(warnings=False, force_reconnect=True) greetings = T.div(_class="userinfo")[login.LoginFragment( original=info)] return ctx.tag[T.a(href="/")[T.img(src="/images/mes-souhaits.png", align="left", alt="Mes souhaits", width=203, height=36)], greetings]
def _renderTag(self, ctx, key, value, readonly): plainTag = widget.TextInput._renderTag(self, ctx, key, value, readonly) return T.span(style="white-space:nowrap")[ plainTag, " ", T.span(class_="fieldlegend")[self.additionalMaterial]]
def _renderTag(self, ctx, key, value, converter, disabled): if not isinstance(value, (list, tuple)): value = [value] # unfortunately, I need to copy all that code from formal to let # me keep multiple selections def renderOptions(ctx, data): if self.noneOption is not None: noneVal = iformal.IKey(self.noneOption).key() option = T.option(value=noneVal)[ iformal.ILabel(self.noneOption).label()] if value is None or value==noneVal: option = option(selected='selected') yield option if data is None: return for item in data: optValue = iformal.IKey(item).key() optLabel = iformal.ILabel(item).label() optValue = converter.fromType(optValue) option = T.option(value=optValue)[optLabel] if optValue in value: option = option(selected='selected') yield option tag = T.select(name=key, id=render_cssid(key), data=self.options)[ renderOptions] if disabled: tag(class_='disabled', disabled='disabled') return T.span(style="white-space:nowrap")[ tag(size=str(self.size), multiple="multiple"), " ", T.span(class_="fieldlegend")[ "No selection matches all, multiple values legal."]]
def test_authenticatedApplicationNavigation(self): """ The I{applicationNavigation} renderer should add primary navigation elements to the tag it is passed if it is called on a L{_PublicPageMixin} being rendered for an authenticated user. """ navigable = FakeNavigableElement(store=self.userStore) installOn(navigable, self.userStore) navigable.tabs = [Tab("foo", 123, 0, [Tab("bar", 432, 0)])] request = FakeRequest() page = self.createPage(self.username) navigationPattern = div[span(id="app-tab", pattern="app-tab"), span(id="tab-contents", pattern="tab-contents")] ctx = context.WebContext(tag=navigationPattern) ctx.remember(request) tag = page.render_applicationNavigation(ctx, None) self.assertEqual(tag.tagName, "div") self.assertEqual(tag.attributes, {}) children = [child for child in tag.children if child.pattern is None] self.assertEqual(children, []) self.assertEqual(len(tag.slotData["tabs"]), 1) fooTab = tag.slotData["tabs"][0] self.assertEqual(fooTab.attributes, {"id": "app-tab"}) self.assertEqual(fooTab.slotData["name"], "foo") fooContent = fooTab.slotData["tab-contents"] self.assertEqual(fooContent.attributes, {"id": "tab-contents"}) self.assertEqual(fooContent.slotData["href"], self.privateApp.linkTo(123))
def test_authenticatedApplicationNavigation(self): """ The I{applicationNavigation} renderer should add primary navigation elements to the tag it is passed if it is called on a L{_PublicPageMixin} being rendered for an authenticated user. """ navigable = FakeNavigableElement(store=self.userStore) installOn(navigable, self.userStore) navigable.tabs = [Tab('foo', 123, 0, [Tab('bar', 432, 0)])] request = FakeRequest() page = self.createPage(self.username) navigationPattern = div[ span(id='app-tab', pattern='app-tab'), span(id='tab-contents', pattern='tab-contents')] ctx = context.WebContext(tag=navigationPattern) ctx.remember(request) tag = page.render_applicationNavigation(ctx, None) self.assertEqual(tag.tagName, 'div') self.assertEqual(tag.attributes, {}) children = [child for child in tag.children if child.pattern is None] self.assertEqual(children, []) self.assertEqual(len(tag.slotData['tabs']), 1) fooTab = tag.slotData['tabs'][0] self.assertEqual(fooTab.attributes, {'id': 'app-tab'}) self.assertEqual(fooTab.slotData['name'], 'foo') fooContent = fooTab.slotData['tab-contents'] self.assertEqual(fooContent.attributes, {'id': 'tab-contents'}) self.assertEqual(fooContent.slotData['href'], self.privateApp.linkTo(123))
def test_authenticatedApplicationNavigation(self): """ The I{applicationNavigation} renderer should add primary navigation elements to the tag it is passed if it is called on a L{_PublicPageMixin} being rendered for an authenticated user. """ navigable = FakeNavigableElement(store=self.userStore) installOn(navigable, self.userStore) navigable.tabs = [Tab('foo', 123, 0, [Tab('bar', 432, 0)])] request = FakeRequest() page = self.createPage(self.username) navigationPattern = div[ span(id='app-tab', pattern='app-tab'), span(id='tab-contents', pattern='tab-contents')] ctx = context.WebContext(tag=navigationPattern) ctx.remember(request) tag = page.render_applicationNavigation(ctx, None) self.assertEqual(tag.tagName, 'div') self.assertEqual(tag.attributes, {}) children = [child for child in tag.children if child.pattern is None] self.assertEqual(children, []) self.assertEqual(len(tag.slotData['tabs']), 1) fooTab = tag.slotData['tabs'][0] self.assertEqual(fooTab.attributes, {'id': 'app-tab'}) self.assertEqual(fooTab.slotData['name'], 'foo') fooContent = fooTab.slotData['tab-contents'] self.assertEqual(fooContent.attributes, {'id': 'tab-contents'}) self.assertEqual( fooContent.slotData['href'], self.privateApp.linkTo(123))
def render(self, data): r = [] i = 0 vlanlist = [] notpresent = T.td(_class="notpresent")[ T.acronym(title="Not present or no information from remote")["N/A"]] for row in data: if row[1] is not None: vlanlist.append(str(row[0])) vid = T.td[T.span(data=row[0], render=T.directive("vlan"))] if row[1] is None: r.append(T.tr(_class=(i%2) and "odd" or "even")[ vid, notpresent, T.td[row[2]]]) elif row[2] is None: r.append(T.tr(_class=(i%2) and "odd" or "even") [vid, T.td[row[1]], notpresent]) elif row[1] == row[2]: r.append(T.tr(_class=(i%2) and "odd" or "even") [vid, T.td(colspan=2)[row[1]]]) else: r.append(T.tr(_class=(i%2) and "odd" or "even") [vid, T.td[row[1]], T.td[row[2]]]) i += 1 vlantable = T.table(_class="vlan")[ T.thead[T.td["VID"], T.td["Local"], T.td["Remote"]], r] return [('VLAN', [[ [T.span(data=v, render=T.directive("vlan")), " "] for v in vlanlist ], T.span(render=T.directive("tooltip"), data=vlantable)], ", ".join(vlanlist))]
def render_description(self, ctx, data): if not data: return ctx.tag["Nothing was found in descriptions"] return ctx.tag["The following descriptions match the request:", T.ul[[ T.li[T.span(_class="data")[d[1]], " from ", T.span(data=d[0], render=T.directive("hostname")), "."] for d in data ]]]
def render_description(self, ctx, data): if not data: return ctx.tag["Nothing was found in descriptions"] return ctx.tag["The following descriptions match the request:", T.ul[ [ T.li [ T.span(_class="data") [d[1]], " from ", T.span(data=d[0], render=T.directive("hostname")), "." ] for d in data ] ] ]
def render_discovery(self, ctx, data): if not data: return ctx.tag["This hostname has not been seen with %s." % self.protocolname] return ctx.tag["This hostname has been seen with %s: " % self.protocolname, T.ul[ [ T.li [ "from port ", T.span(_class="data") [d[1]], " of ", T.span(data=d[0], render=T.directive("hostname")) ] for d in data ] ] ]
def render_ipeqt(self, ctx, data): if not data: return ctx.tag["The IP ", T.span(data=self.ip, render=T.directive("ip")), " is not owned by a known equipment."] return ctx.tag["The IP ", T.span(data=self.ip, render=T.directive("ip")), " belongs to ", T.span(data=data[0][0], render=T.directive("hostname")), "."]
def render_discovery(self, ctx, data): if not data: return ctx.tag["This hostname has not been seen with %s." % self.protocolname] return ctx.tag[ "This hostname has been seen with %s: " % self.protocolname, T.ul[[ T.li["from port ", T.span(_class="data")[d[1]], " of ", T.span(data=d[0], render=T.directive("hostname"))] for d in data ]]]
def addTickAtTime(self, t): dt = datetime.fromtimestamp(t) label = [T.span(class_="date")[dt.strftime("%Y-")], (T.span(class_="date")[dt.strftime("%m-%d")], T.br), dt.strftime("%H:%M")] visibleLabel = differentSuffix(label, self.prevLabel, key=str) self.output.append( T.div(class_="abs timeline-timeLabel", style=("left: %spx; top: 50px; height: 50px;" % xPx(t)))[visibleLabel]) self.prevLabel = label
def rend(self, ctx, data): return (tags.span( _class="collapser-line", onclick=("collapse(this, '", self.headCollapsed, "', '", self.headExpanded, "');") )[tags.img(_class="visibilityImage", src="/images/outline-%s.png" % self.collapsed), tags.span( _class="headText", style="color: blue; text-decoration: underline; cursor: pointer;" )[self.collapsed == 'collapsed' and self.headCollapsed or self.headExpanded]], tags.xml(' '), tags.div(_class=self.collapsed)[self.body])
def _renderPage(): page = MantissaLivePage(FakeWebSite()) element = LiveElement(stan(tags.span(render=tags.directive('liveElement')))) element.setFragmentParent(page) element.jsClass = u'Mantissa.Test.Dummy.DummyWidget' page.docFactory = stan([tags.span(render=tags.directive('liveglue')), element]) ctx = WovenContext() req = FakeRequest(headers={'host': self.hostname}) ctx.remember(req, IRequest) page.beforeRender(ctx) page.renderHTTP(ctx) page._messageDeliverer.close()
def render_sonmp(self, ctx, data): if not data: return ctx.tag["This IP has not been seen with SONMP."] return ctx.tag["This IP has been seen with SONMP: ", T.ul[ [ T.li [ "from port ", T.span(_class="data") [d[1]], " of ", T.span(data=d[0], render=T.directive("hostname")), " connected to port ", T.span(data=d[2], _class="data", render=T.directive("sonmpport")) ] for d in data] ] ]
def addTickAtTime(self, t): dt = datetime.fromtimestamp(t) label = [ T.span(class_="date")[dt.strftime("%Y-")], (T.span(class_="date")[dt.strftime("%m-%d")], T.br), dt.strftime("%H:%M") ] visibleLabel = differentSuffix(label, self.prevLabel, key=str) self.output.append( T.div(class_="abs timeline-timeLabel", style=("left: %spx; top: 50px; height: 50px;" % xPx(t)))[visibleLabel]) self.prevLabel = label
def render_sonmp(self, ctx, data): if not data: return ctx.tag["This IP has not been seen with SONMP."] return ctx.tag["This IP has been seen with SONMP: ", T.ul[[ T. li["from port ", T.span(_class="data")[d[1]], " of ", T.span(data=d[0], render=T.directive("hostname")), " connected to port ", T. span(data=d[2], _class="data", render=T.directive("sonmpport"))] for d in data ]]]
def _renderPage(): page = MantissaLivePage(FakeWebSite()) element = LiveElement( stan(tags.span(render=tags.directive('liveElement')))) element.setFragmentParent(page) element.jsClass = u'Mantissa.Test.Dummy.DummyWidget' page.docFactory = stan( [tags.span(render=tags.directive('liveglue')), element]) ctx = WovenContext() req = FakeRequest(headers={'host': self.hostname}) ctx.remember(req, IRequest) page.beforeRender(ctx) page.renderHTTP(ctx) page._messageDeliverer.close()
def maybeShortenList(system, label, lst, idbase): lst2 = [] for name in lst: o = system.allobjects.get(name) if o is None or o.isVisible: lst2.append(name) lst = lst2 if not lst: return None def one(item): if item in system.allobjects: return taglink(system.allobjects[item]) else: return item def commasep(items): r = [] for item in items: r.append(one(item)) r.append(', ') del r[-1] return r p = [label] if len(lst) <= 5 or not system.options.htmlshortenlists: p.extend(commasep(lst)) else: p.extend(commasep(lst[:3])) q = [', '] q.extend(commasep(lst[3:])) q.append( tags.span(class_='showIfJS') [' ', tags.a(href="#", onclick="showAndHide('%s');" % idbase, class_="jslink")['(hide last %d again)' % len(lst[3:])]]) p.append(tags.span(id=idbase, class_='hideIfJS')[q]) p.append( tags.span( id=idbase + 'Link', class_='showIfJS')[' ', tags.a(href="#", onclick="hideAndShow('%s');" % idbase, class_="jslink")['... and %d more' % len(lst[3:])]]) return p
def render_listsheets(self,ctx): return [T.div[ T.span(style="font-weight:bold;")[ T.a(href=i[0])[i[1]]],' located at ', T.a(href=i[0])[i[0]] ] for i in self.emailInfo]
def render_comment(self, ctx, comment): tag = ctx.tag tag.fillSlots("id", comment.id) tag.fillSlots("posted", comment.posted) tag.fillSlots("authorName", comment.authorName) if comment.authorName == 'David Ward': tag.fillSlots("isOwner", 'owner') else: tag.fillSlots("isOwner", '') tag.fillSlots("authorEmail", comment.authorEmail) tag.fillSlots("comment", T.xml(markdown.markdown(comment.comment))) tag.fillSlots("relatesToCommentId",comment.relatesToCommentId) if hasattr(comment, 'relatesToComment') and comment.relatesToComment is not None: tag.fillSlots("relatesToCommentName",comment.relatesToComment.authorName) else: tag.fillSlots("relatesToCommentName",'main blog entry') if hasattr(comment,'followUpComments') and comment.followUpComments is not None: fTag = T.span(class_='followUps') for f in comment.followUpComments: fTag[ T.a(href="#comment-%s"%f.id,rel='inspires')[ f.authorName ],', ' ] tag.fillSlots("followUpComments",fTag) else: tag.fillSlots("followUpComments",'None') return tag
class LiveStatusFragment(athena.LiveFragment): docFactory = loaders.stan(tags.span(render=tags.directive('liveFragment'))) jsClass = u'Quotient.Grabber.StatusWidget' _pending = False _pendingStatus = None def __init__(self, status): self.status = status def statusChanged(self, newStatus): if self._pending: self._pendingStatus = newStatus else: self._pending = True self.callRemote('setStatus', newStatus).addCallback(self._unpend) def _unpend(self, ign): pendingStatus = self._pendingStatus self._pendingStatus = None self._pending = False if pendingStatus is not None: self.statusChanged(pendingStatus) def startObserving(self): self.removeObserver = self.status.addChangeObserver(self.statusChanged) return self.status.message expose(startObserving)
def rend(self, context, data): defaults = context.locate(iformless.IFormDefaults) value = defaults.getDefault(context.key, context) context.remember(data.typedValue, iformless.ITyped) if data.typedValue.getAttribute('immutable'): inp = tags.span(id=keyToXMLID(context.key))[value] else: ##value may be a deferred; make sure to wait on it properly before calling self.input ## TODO: If flattening this results in an empty string, return an empty string inp = tags.invisible(render=lambda c, value: self.input( context, tags.invisible(), data, data.name, value), data=value) if data.typedValue.getAttribute( 'hidden') or data.typedValue.getAttribute('compact'): return inp context.fillSlots('label', data.label) context.fillSlots('name', data.name) context.fillSlots('input', inp) context.fillSlots('error', getError(context)) context.fillSlots('description', data.description) context.fillSlots('id', keyToXMLID(context.key)) context.fillSlots('value', value) return context.tag
def ret(ethtool): state = False rate = "Unknown" for n in ethtool.split('\n'): l = n.strip() if not ':' in l: continue l = n.strip().split(':') k = l[0].strip() v = l[1].strip() if k == 'Link detected': state = v == 'yes' if k == 'Speed': rate = v if not state: rate = "Not Connected" if doState: green = "#29b25c" red = "#bf0000" img = state and '/images/state-running.png' or '/images/state-stopped-whitebg.png' color = state and green or red return [ tags.td[tags.img(src=img)], tags.td( width="100%")[entities.nbsp, tags.span( style="color: %s" % color)["Ethernet connection (%s)" % (iface)]], ] return ctx.tag["%s" % rate]
def test_nested_data(self): def checkContext(ctx, data): self.assertEquals(data, "inner") self.assertEquals(ctx.locate(inevow.IData, depth=2), "outer") return 'Hi' tag = tags.html(data="outer")[tags.span(render=lambda ctx,data: ctx.tag, data="inner")[checkContext]] self.assertEquals(self.render(tag), "<html><span>Hi</span></html>")
def gotProducts(products): htmlblock = [] for n,product in enumerate(products): column = divmod(n,3)[1]+1 name = product.code title = product.title shortDescription = product.summary imgsrc='/system/ecommerce/%s/mainImage?size=190x300&sharpen=1.0x0.5%%2b0.8%%2b0.1'%product.id html = T.div(class_='category c%s'%column)[ T.a(href=url.here.child(name))[ T.img(src=imgsrc,width=190),T.span(class_='mbf-item')['#gallery %s'%product.code] ], T.h4[ T.a(href=url.here.child(name))[ title ] ], T.p[ T.a(href=url.here.child(name))[ shortDescription ] ] ] htmlblock.append(html) # Group the output into threes if column == 3: out = htmlblock htmlblock = [] yield T.div(class_="threecolumnleft clearfix")[ out ] # and then yield anything left over if the last item wasn't at the end of a row if column != 3: yield T.div(class_="threecolumnleft clearfix")[ htmlblock ]
def render(self, ctx, key, args, errors): # The whole plan sucks -- these should have been two separate widgets children = [] if '_DBOPTIONS' in args: # we're working from pre-parsed (nevow formal) arguments v = [[args["_DBOPTIONS"]["order"]] or "", [args["_DBOPTIONS"]["limit"] or 100], [args["_DBOPTIONS"]["direction"] or "ASC"]] else: # args come raw from nevow contexts v = [args.get("_DBOPTIONS_ORDER", ['']), args.get("MAXREC", [100]), args.get("_DBOPTIONS_DIR", "ASC")] if errors: args = {"_DBOPTIONS_ORDER": v[0], "MAXREC": v[1], "_DBOPTIONS_DIR": v[2]} else: args = {"_DBOPTIONS_ORDER": v[0][0], "MAXREC": int(v[1][0]), "_DBOPTIONS_DIR": v[2][0]} if self.sortWidget: children.extend(["Sort by ", self.sortWidget.render(ctx, "_DBOPTIONS_ORDER", args, errors), " "]) children.extend([" ", self.directionWidget.render(ctx, "_DBOPTIONS_DIR", args, errors)]) if self.limitWidget: children.extend([T.br, "Limit to ", self.limitWidget.render(ctx, "MAXREC", args, errors), " items."]) return T.span(id=render_cssid(key))[children]
def workloadTypeList(self, ctx): session = inevow.ISession(ctx) wltTable = WorkloadTypeTable(self, session.uid) if self.workloadTypes is None: self.workloadTypes = yield session.agent.expsvcAgent.getWorkloadTypes(agentId = self.agentId) self.workloadClasses = ['CPU', 'MEM', 'DISK', 'FS', 'NET', 'OS'] for wltypeName, wltype in self.workloadTypes.iteritems(): wlcTags = [T.span(_class='badge', title = wlclasses[wlc][1])[ wlclasses[wlc][0]] for wlc in wltype.wlclass] rawClasses = set(wlclasses[wlc][0] for wlc in wltype.wlclass) wltTable.add({'module': wltype.module, 'workload': wltypeName, # url.gethere doesn't work here because when liveglue updates page # all links become broken. 'wltHref': url.URL.fromContext(ctx).add('wlt', wltypeName), 'classes': wlcTags, 'rawClasses': rawClasses}) wltTable.setPage(0) self.wltTable = wltTable returnValue(wltTable)
class R(rend.Page): def data_numbers(context, data): return ['one', 'two', 'three'] tags = ul(data=data_numbers, render=directive('sequence'))[li( pattern='item')[span(render=str)]] docFactory = loaders.stan(tags)
def render_index_players(self, ctx, data): data.sort(key=attrgetter('name')) lines = [] for player in data: line = [] name = player.name tzid = player.tzid tzidcell = T.td(_class="objtzid")[tzid, ':'] line.append(tzidcell) if admin.verify(player): line.append(T.td['!']) elif wizard.verify(player): line.append(T.td['@']) else: line.append(T.td) editlink = T.a(href="/edit/%s" % tzid)[name] line.append(T.td(_class="objname")[editlink]) if player.logged_in: room = player.room editlink = "/edit/%s" % room.tzid link = T.a(href=editlink)[T.span(_class="editlink")[room.name]] line.append(T.td[link]) else: line.append(T.td) lines.append(T.tr[line]) return T.table[lines]
def rend(self, context, data): defaults = context.locate(iformless.IFormDefaults) value = defaults.getDefault(context.key, context) context.remember(data.typedValue, iformless.ITyped) if data.typedValue.getAttribute('immutable'): inp = tags.span(id=keyToXMLID(context.key))[value] else: ##value may be a deferred; make sure to wait on it properly before calling self.input ## TODO: If flattening this results in an empty string, return an empty string inp = tags.invisible( render=lambda c, value: self.input( context, tags.invisible(), data, data.name, value ), data=value) if data.typedValue.getAttribute('hidden') or data.typedValue.getAttribute('compact'): return inp context.fillSlots( 'label', data.label ) context.fillSlots( 'name', data.name ) context.fillSlots( 'input', inp ) context.fillSlots( 'error', getError(context) ) context.fillSlots( 'description', data.description ) context.fillSlots( 'id', keyToXMLID(context.key) ) context.fillSlots( 'value', value ) return context.tag
class SearchIPInDiscovery(rend.Fragment, RenderMixIn): docFactory = loaders.stan( T.span(render=T.directive("discovery"), data=T.directive("discovery"))) discovery_name = "unknown" def __init__(self, dbpool, ip): self.ip = ip self.dbpool = dbpool rend.Fragment.__init__(self) def render_discovery(self, ctx, data): if not data: return ctx.tag["This IP has not been seen with %s." % self.discovery_name] return ctx.tag[ "This IP has been seen with %s: " % self.discovery_name, T.ul[[ T.li["from port ", T.span(_class="data")[d[1]], " of ", T.span(data=d[0], render=T.directive("hostname")), " connected to port ", T.span(_class="data")[d[2]], " of ", T.span(data=d[3], render=T.directive("hostname"))] for d in data ]]]
def test_patterned(self): """Test fetching a specific part (a pattern) of the document. """ doc = t.div[t.p[t.span(pattern='inner')['something']]] df = loaders.stan(doc, pattern='inner') self.assertEquals(df.load()[0].tagName, 'span') self.assertEquals(df.load()[0].children[0], 'something')
class SearchIPInSonmp(rend.Fragment, RenderMixIn): docFactory = loaders.stan( T.span(render=T.directive("sonmp"), data=T.directive("sonmp"))) def __init__(self, dbpool, ip): self.ip = ip self.dbpool = dbpool rend.Fragment.__init__(self) def data_sonmp(self, ctx, data): return self.dbpool.runQueryInPast( ctx, "SELECT e.name, p.name, s.remoteport " "FROM equipment_full e, port_full p, sonmp_full s " "WHERE s.remoteip=%(ip)s " "AND s.port=p.index AND p.equipment=e.ip " "AND s.equipment=e.ip " "AND e.deleted='infinity' AND p.deleted='infinity' " "AND s.deleted='infinity' " "ORDER BY e.name", {'ip': self.ip}) def render_sonmp(self, ctx, data): if not data: return ctx.tag["This IP has not been seen with SONMP."] return ctx.tag["This IP has been seen with SONMP: ", T.ul[[ T. li["from port ", T.span(_class="data")[d[1]], " of ", T.span(data=d[0], render=T.directive("hostname")), " connected to port ", T. span(data=d[2], _class="data", render=T.directive("sonmpport"))] for d in data ]]]
class SearchInDescription(rend.Fragment, RenderMixIn): docFactory = loaders.stan( T.span(render=T.directive("description"), data=T.directive("description"))) def __init__(self, dbpool, name): self.dbpool = dbpool self.name = name rend.Fragment.__init__(self) def data_description(self, ctx, data): return self.dbpool.runQueryInPast( ctx, "SELECT DISTINCT name, description " "FROM equipment_full " "WHERE deleted='infinity' " "AND description ILIKE '%%' || %(name)s || '%%'", {'name': self.name}) def render_description(self, ctx, data): if not data: return ctx.tag["Nothing was found in descriptions"] return ctx.tag["The following descriptions match the request:", T.ul[[ T.li[T.span(_class="data")[d[1]], " from ", T.span(data=d[0], render=T.directive("hostname")), "."] for d in data ]]]
class SearchIPInEquipment(rend.Fragment, RenderMixIn): docFactory = loaders.stan( T.span(render=T.directive("ipeqt"), data=T.directive("ipeqt"))) def __init__(self, dbpool, ip): self.ip = ip self.dbpool = dbpool rend.Fragment.__init__(self) def data_ipeqt(self, ctx, data): return self.dbpool.runQueryInPast( ctx, "SELECT e.name FROM equipment_full e " "WHERE e.ip=%(ip)s AND e.deleted='infinity'", {'ip': self.ip}) def render_ipeqt(self, ctx, data): if not data: return ctx.tag["The IP ", T.span(data=self.ip, render=T.directive("ip")), " is not owned by a known equipment."] return ctx.tag["The IP ", T.span(data=self.ip, render=T.directive("ip")), " belongs to ", T.span(data=data[0][0], render=T.directive("hostname")), "."]
class SearchHostnameWithDiscovery(rend.Fragment, RenderMixIn): docFactory = loaders.stan( T.span(render=T.directive("discovery"), data=T.directive("discovery"))) def __init__(self, dbpool, name): self.name = name self.dbpool = dbpool rend.Fragment.__init__(self) def data_discovery(self, ctx, data): return self.dbpool.runQueryInPast( ctx, "SELECT e.name, p.name " "FROM equipment_full e, port_full p, " + self.table + " l " "WHERE (l.sysname=%(name)s OR l.sysname ILIKE %(name)s || '%%') " "AND l.port=p.index AND p.equipment=e.ip " "AND l.equipment=e.ip " "AND e.deleted='infinity' AND p.deleted='infinity' " "AND l.deleted='infinity' " "ORDER BY e.name", {'name': self.name}) def render_discovery(self, ctx, data): if not data: return ctx.tag["This hostname has not been seen with %s." % self.protocolname] return ctx.tag[ "This hostname has been seen with %s: " % self.protocolname, T.ul[[ T.li["from port ", T.span(_class="data")[d[1]], " of ", T.span(data=d[0], render=T.directive("hostname"))] for d in data ]]]
class SearchMacInInterfaces(rend.Fragment, RenderMixIn): docFactory = loaders.stan( T.span(render=T.directive("macif"), data=T.directive("macif"))) def __init__(self, dbpool, mac): self.mac = mac self.dbpool = dbpool rend.Fragment.__init__(self) def data_macif(self, ctx, data): return self.dbpool.runQueryInPast( ctx, "SELECT DISTINCT e.name, e.ip, p.name, p.index " "FROM equipment_full e, port_full p " "WHERE p.mac=%(mac)s " "AND p.equipment=e.ip " "AND e.deleted='infinity' " "AND p.deleted='infinity' " "ORDER BY e.name, p.index", {'mac': self.mac}) def render_macif(self, ctx, data): if not data: return ctx.tag["I did not find this MAC on any interface."] return ctx.tag[ "This MAC was found on the following interfaces: ", T.ul[[ T.li[T.invisible(data=l[0], render=T.directive("hostname")), " (", T.invisible(data=l[1], render=T.directive("ip")), ") " "interface ", T.span(_class="data")[l[2]]] for l in data ]]]
def test_nested_data(self): def checkContext(ctx, data): self.assertEqual(data, "inner") self.assertEqual(ctx.locate(inevow.IData, depth=2), "outer") return 'Hi' tag = tags.html(data="outer")[tags.span(render=lambda ctx,data: ctx.tag, data="inner")[checkContext]] self.assertEqual(self.render(tag), "<html><span>Hi</span></html>")
def getWidgets(self): widgets = [] f = athena.LiveFragment(docFactory=loaders.stan(tags.div[widgets])) f.setFragmentParent(self) for i in xrange(5): widgets.append(athena.LiveFragment(docFactory=loaders.stan(tags.span(render=tags.directive('liveFragment'))))) widgets[-1].setFragmentParent(f) return f
def setUp(self): self.d = Deferred() self.d2 = Deferred() self.r = rend.Page(docFactory=loaders.stan( tags.html(data=self.data_later)[ 'Hello ', str, ' and ' 'goodbye ',str, tags.span(data=self.data_later2, render=str)]))
def render_dns(self, ctx, name): try: name = str(name[0][0].payload.name) except: return ctx.tag["This IP has no known name in DNS."] return ctx.tag["This IP is associated to ", T.span(data=name, render=T.directive("hostname")), " in DNS."]
def render_sample(self, context, data): request = inevow.IRequest(context) session = inevow.ISession(context) count = getattr(session, 'count', 1) session.count = count + 1 return ["Welcome, person from ", request.client.host, "! You are using ", request.getHeader('user-agent'), " and have been here ", T.span(id="count")[count], " times."]
def rend(self, ctx, data): return (tags.span( _class="collapser-line", onclick=( "collapse(this, '", self.headCollapsed, "', '", self.headExpanded, "');"))[ tags.img(_class="visibilityImage", src="/images/outline-%s.png" % self.collapsed), tags.span(_class="headText", style="color: blue; text-decoration: underline; cursor: pointer;")[ self.collapsed == 'collapsed' and self.headCollapsed or self.headExpanded ] ], tags.xml(' '), tags.div(_class=self.collapsed)[ self.body ])
def gotAll(items,categories,products): categoryCMSItems = {} for item in items: i = item.getProtectedObject() categoryCMSItems[i.name] = i categoryCMSItemMainImage = {} categoryCMSItemCode = {} for categoryCMSItem in categoryCMSItems.values(): category = categoryCMSItem.name for product in products: if u'gallery.%s'%category in product.categories: match = product categoryCMSItemMainImage[categoryCMSItem.name] = match.id categoryCMSItemCode[categoryCMSItem.name] = match.code break htmlblock = [] for n, category in enumerate(categories.children): name = category.textid categoryCMSItem = categoryCMSItems.get(name,None) column = divmod(n,3)[1]+1 try: title = categoryCMSItem.title shortDescription = categoryCMSItem.shortDescription except AttributeError: title = category.label shortDescription = '' try: imgsrc='/system/ecommerce/%s/mainImage?size=190x300&sharpen=1.0x0.5%%2b0.7%%2b0.1'%categoryCMSItemMainImage[name] except KeyError: imgsrc='/skin/images/spacer.gif' html = T.div(class_='category c%s'%column)[ T.a(href=url.here.child(name))[ T.img(src=imgsrc,width=190),T.span(class_='mbf-item')['#gallery %s'%categoryCMSItemCode[name]] ], T.h4[ T.a(href=url.here.child(name))[ title ] ], T.p[ T.a(href=url.here.child(name))[ shortDescription ] ] ] htmlblock.append(html) # Group the output into threes if column == 3: out = htmlblock htmlblock = [] yield T.div(class_="threecolumnleft clearfix")[ out ] # and then yield anything left over if the last item wasn't at the end of a row if column != 3: yield T.div(class_="threecolumnleft clearfix")[ htmlblock ]
def test_startMenuSetsTabURLs(self): """ L{Tabs<Tab>} which have C{None} for a C{linkURL} attribute should have a value set for that attribute based on the L{IWebTranslator} passed to L{startMenu}. """ tab = webnav.Tab("alpha", 123, 0) webnav.startMenu(FakeTranslator(), [tab], tags.span()) self.assertEqual(tab.linkURL, "/link/123")
def add_item(self, item): k = unicode(str(hash(item)), 'ascii') self._models.append(item) self._labels[k] = Label(k) self._labels[k].page = self.page i = T.span(id=u'_%s' % k, style='{cursor: pointer}')[ athena.handler(event='onclick', handler='changed'), self._labels[k]] self._items.append(i)
def test_settingsLink(self): """ L{settingsLink} should add a link to the settings item supplied as a child of the tag supplied. """ self.storeID = 123 node = tags.span() tag = webnav.settingsLink(FakeTranslator(), self, node) self.assertEqual(tag.tagName, "span") self.assertEqual(tag.children, ["/link/123"])
def render_header(self, ctx, data): si_s = abbreviated_dirnode(self.node) header = ["Tahoe-LAFS Directory SI=", T.span(class_="data-chars")[si_s]] if self.node.is_unknown(): header.append(" (unknown)") elif not self.node.is_mutable(): header.append(" (immutable)") elif self.node.is_readonly(): header.append(" (read-only)") return ctx.tag[header]
def maybeShortenList(system, label, lst, idbase): lst2 = [] for name in lst: o = system.allobjects.get(name) if o is None or o.isVisible: lst2.append(name) lst = lst2 if not lst: return None def one(item): if item in system.allobjects: return taglink(system.allobjects[item]) else: return item def commasep(items): r = [] for item in items: r.append(one(item)) r.append(', ') del r[-1] return r p = [label] if len(lst) <= 5 or not system.options.htmlshortenlists: p.extend(commasep(lst)) else: p.extend(commasep(lst[:3])) q = [', '] q.extend(commasep(lst[3:])) q.append(tags.span(class_='showIfJS')[ ' ', tags.a(href="#", onclick="showAndHide('%s');"%idbase, class_="jslink") ['(hide last %d again)'%len(lst[3:])]]) p.append(tags.span(id=idbase, class_='hideIfJS')[q]) p.append(tags.span(id=idbase+'Link', class_='showIfJS')[ ' ', tags.a(href="#", onclick="hideAndShow('%s');"%idbase, class_="jslink") ['... and %d more'%len(lst[3:])]]) return p
def render_tooltip(self, ctx, data): return T.invisible[ T.a(_class="tt")[" [?] "], T.span(_class="tooltip")[ T.div(_class="tooltipactions")[ T.ul[ T.li(_class="closetooltip")[ " [ ", T.a(href="#")["close"], " ]"]]], data]]