def test_url(self):
        """
        An L{URL} object is flattened to the appropriate representation of
        itself, whether it is the child of a tag or the value of a tag
        attribute.
        """
        link = URL.fromString("http://foo/fu?bar=baz&bar=baz#quux%2f")
        self.assertStringEqual(
            self.flatten(link),
            "http://foo/fu?bar=baz&bar=baz#quux%2F")
        self.assertStringEqual(
            self.flatten(div[link]),
            '<div>http://foo/fu?bar=baz&amp;bar=baz#quux%2F</div>')
        self.assertStringEqual(
            self.flatten(div(foo=link)),
            '<div foo="http://foo/fu?bar=baz&amp;bar=baz#quux%2F"></div>')
        self.assertStringEqual(
            self.flatten(div[div(foo=link)]),
            '<div><div foo="http://foo/fu?bar=baz&amp;bar=baz#quux%2F"></div>'
            '</div>')

        link = URL.fromString("http://foo/fu?%2f=%7f")
        self.assertStringEqual(
            self.flatten(link),
            "http://foo/fu?%2F=%7F")
        self.assertStringEqual(
            self.flatten(div[link]),
            '<div>http://foo/fu?%2F=%7F</div>')
        self.assertStringEqual(
            self.flatten(div(foo=link)),
            '<div foo="http://foo/fu?%2F=%7F"></div>')
示例#2
0
    def visit_cmsimage_node(self, node):
        maxwidth=node.attributes['maxwidth']
        maxheight=node.attributes['maxheight']
            
        if maxwidth is None or maxheight is None:
            tag = T.img(src=self.systemURL.child('assets').child( node.attributes['id'] ))
        else:
            tag = T.img(src=self.systemURL.child('assets').child( node.attributes['id'] ).add('size','%sx%s'%(maxwidth,maxheight)))
        
        if node.attributes['alt']:
            tag = tag(alt=node.attributes['alt'])
        if node.attributes['title']:
            tag = tag(title=node.attributes['title'])
        if node.attributes['cssclass']:
            tag = tag(class_=node.attributes['cssclass'])
        if node.attributes['href']:
            tag = T.a(href=node.attributes['href'])[ tag ]
            
        if node.attributes['caption']:
            tag = T.div(class_='cmsimage')[tag,T.p[node.attributes['caption']]]
        else:
            tag = T.div(class_='cmsimage')[tag]
        html = flat.flatten(tag)

        self.body.append(html)
示例#3
0
 def rend(self, *junk):
     (l, middle, r) = self.extract.inContext()
     return tags.div(class_='extract-container')[
             l,
             tags.div(class_='extract-text')[
                 tags.span[middle]],
             r]
示例#4
0
    def calculateDefaultSkin(self, context):
        if self.isGrouped:
            frm = tags.invisible
            butt = ""
            fld = tags.invisible
        else:
            frm = tags.form(
                id=slot("form-id"),
                name=slot("form-id"),
                action=slot("form-action"),
                method="post",
                enctype="multipart/form-data",
                **{"accept-charset": "utf-8"}
            )
            butt = slot("form-button")
            fld = tags.fieldset[tags.input(type="hidden", name="_charset_")]

        ## Provide default skin since no skin was provided for us.
        context.tag.clear()[
            frm[
                fld[
                    tags.legend(_class="freeform-form-label")[slot("form-label")],
                    tags.div(_class="freeform-form-description")[slot("form-description")],
                    tags.div(_class="freeform-form-error")[slot("form-error")],
                    slot("form-arguments"),
                    butt,
                ]
            ]
        ]
	def render_content(self, ctx, data):
		request = inevow.IRequest(ctx)
		
		ctx.fillSlots('header_bar', self.anon_header) 
		ctx.fillSlots('top_bar', T.div(id="top_bar"))
		ctx.fillSlots('main_content', loaders.stan(T.div(id="manager_hook")))
		return ctx.tag
示例#6
0
 def test_applicationNavigationChildren(self):
     """
     The L{applicationNavigation} renderer should fill the 'subtabs' slot
     with copies of the 'subtab' pattern for each tab, if that pattern is
     present.  (This is only tested to one level of depth because we
     currently only support one level of depth.)
     """
     tag = self._renderAppNav(
         [
             webnav.Tab("alpha", 123, 0),
             webnav.Tab("beta", 234, 0, children=[webnav.Tab("gamma", 345, 0), webnav.Tab("delta", 456, 0)]),
         ],
         tags.span[
             tags.div(pattern="app-tab"),
             tags.div(pattern="tab-contents"),
             tags.div(pattern="subtab"),
             tags.div(pattern="subtab-contents", class_="subtab-contents-class"),
         ],
     )
     navTags = list(tag.slotData["tabs"])
     self.assertEqual(len(navTags), 2)
     alpha, beta = navTags
     self.assertEqual(alpha.slotData["subtabs"], [])
     self.assertEqual(len(beta.slotData["subtabs"]), 2)
     subtab1 = beta.slotData["subtabs"][0]
     self.assertEqual(subtab1.slotData["name"], "gamma")
     self.assertEqual(subtab1.slotData["href"], "/link/345")
     self.assertEqual(subtab1.slotData["tab-contents"].attributes["class"], "subtab-contents-class")
     subtab2 = beta.slotData["subtabs"][1]
     self.assertEqual(subtab2.slotData["name"], "delta")
     self.assertEqual(subtab2.slotData["href"], "/link/456")
     self.assertEqual(subtab2.slotData["tab-contents"].attributes["class"], "subtab-contents-class")
示例#7
0
 def render_footer(self, context, data):
     return  tags.p() [
             tags.div()['Lumen is running on port %s' % lumen.config['port']],
             tags.div()[
                 tags.a(href='http://github.com/unsouled/lumen')['Github']
             ]
     ]
示例#8
0
 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 ]
示例#9
0
文件: homepage.py 项目: drewp/magma
def divBar(text, width, fraction, barColor):
    fraction = min(1, max(0, fraction))
    sp = T.raw("&nbsp;")
    return T.div(class_="bar", style="width: %spx;" % width)[
        T.div(class_="fill", style="width: %dpx; background: %s" % (width * fraction, barColor))[sp],
        T.div(class_="txt")[text],
        sp,
    ]
示例#10
0
        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 ]
示例#11
0
 def render_body(self, ctx, data):
     for j in range(self.maxNodes // self.maxDepth):
         top = t = tags.div()
         for i in range(self.maxDepth):
             m = tags.div()
             t[m]
             t = m
         t[InitializationBenchmark(self)]
         yield top
 def progressBar(self, ctx, data):
     name = data.get('name', 'theProgressBar')
     percent = data.get('percent', 0)
     yield t.div(class_='progressBar', id_=str(name))[
         t.div(class_ ='progressBarDiv', style='width: %i%%'%percent) ]
     yield t.script(type='text/javascript')[
         component[name].init('new ProgressBar(%r)'%name),
         #component[name].setPercent(percent)
     ]
示例#13
0
 def getWidgetDocument(self):
     """
     Return part of a document which contains some explicitly sized
     elements.  The client portion of this test will retrieve them by their
     class value and assert things about their size.
     """
     return tags.div[
         tags.div(class_='foo', style='height: 126px; width: 1px'),
         tags.div(class_='bar', style='padding: 1px 2px 3px 4px; height: 12px; width: 70px')]
示例#14
0
    def render_middle(self, context, data):
        yield T.div(render=T.directive('trail'), data=data.get_ancestry())
        yield T.h1(class_='main-heading')[data.title]

        yield T.div(render=T.directive('items'), data=data.get_subdirs())

        yield T.div(render=T.directive('rst'))      

        yield T.div(render=T.directive('items'), data=data.get_items())
示例#15
0
文件: htmleditor.py 项目: bne/squeal
 def renderImmutable(self, ctx, key, args, errors):
     value = iformal.IStringConvertible(self.original).fromType(args.get(key))
     if value:
         value=T.xml(value)
     else:
         value=''
     return T.div(id=key, class_="readonly-textarea-container") [
         T.div(class_='readonly-textarea readonly')[value]
     ]
示例#16
0
文件: form.py 项目: bne/squeal
    def render_field(self, ctx, data):

        # The field we're rendering
        field = self.field

        # Get stuff from the context
        formData = iformal.IFormData(ctx)
        formErrors = iformal.IFormErrors(ctx, None)

        # Find any error
        if formErrors is None:
            error = None
        else:
            error = formErrors.getFieldError(field.key)

        # Build the error message
        if error is None:
            message = ''
        else:
            message = T.div(class_='message')[error.message]

        # Create the widget (it's created in __init__ as a hack)
        widget = self.widget

        # Build the list of CSS classes
        classes = [
            'field',
            field.type.__class__.__name__.lower(),
            widget.__class__.__name__.lower(),
            ]
        if field.type.required:
            classes.append('required')
        if field.cssClass:
            classes.append(field.cssClass)
        if error:
            classes.append('error')

        # Create the widget and decide the method that should be called
        if field.type.immutable:
            render = widget.renderImmutable
        else:
            render = widget.render

        # Fill the slots
        tag = ctx.tag
        tag.fillSlots('id', util.render_cssid(field.key))
        tag.fillSlots('fieldId', [util.render_cssid(field.key), '-field'])
        tag.fillSlots('class', ' '.join(classes))
        tag.fillSlots('label', field.label)
        tag.fillSlots('inputs', render(ctx, field.key, formData,
            formErrors))
        tag.fillSlots('message', message)
        tag.fillSlots('description',
                T.div(class_='description')[field.description or ''])

        return ctx.tag
 def test_stringTagAttributes(self):
     """
     C{str} L{Tag} attribute values are flattened by applying XML attribute
     value quoting rules.
     """
     self.assertStringEqual(
         self.flatten(div(foo="bar")), '<div foo="bar"></div>')
     self.assertStringEqual(
         self.flatten(div(foo='"><&')),
         '<div foo="&quot;&gt;&lt;&amp;"></div>')
示例#18
0
文件: test_json.py 项目: StetHD/nevow
 def _doubleLiveSerialization(self, cls, renderer):
     livePage = DummyLivePage()
     liveFragment = cls(
         docFactory=loaders.stan(
             [tags.div(render=tags.directive(renderer))['Hello'],
              tags.div(render=tags.directive('foo'))]))
     liveFragment.setFragmentParent(livePage)
     self.assertEqual(
         json.serialize(liveFragment),
         json.serialize(liveFragment))
        def _render(self, ctx, key, args, errors, value, tag):
            def data_facets(ctx, data):

                storeSession = util.getStoreSession(ctx)
                avatar = util.getAvatar(ctx)

                @defer.deferredGenerator
                def loadCategories(facets):
                    d = defer.waitForDeferred(avatar.getCategoryManager(storeSession))
                    yield d
                    categories = d.getResult()
                    rv = []
                    for f in facets:
                        facetData = FacetData()
                        facetData.label = f[2]
                        facetData.textid = f[1]
                        rv.append(facetData)
                        d = defer.waitForDeferred(categories.loadCategories(facetData.textid))
                        yield d
                        facetData.tree = d.getResult().children
                    yield rv

                d = avatar.getCategoryManager(storeSession)
                d.addCallback(lambda categories: categories.loadFacets())
                d.addCallback(loadCategories)
                return d

            def render_facet(ctx, data):
                tag = ctx.tag
                tag.fillSlots("facetlabel", data.label)
                return tag

            def render_node(ctx, data):
                tag = ctx.tag
                tag.fillSlots("value", data.path)
                tag.fillSlots("label", data.label)
                if data.path in value:
                    tag.children[0] = tag.children[0](checked="checked")
                else:
                    tag.children[0](checked=None)
                return tag

            template = T.div(class_="categorieswidget")[
                T.p(class_="opener")["click to open/close"],
                T.ul(class_="panel", data=data_facets, render=rend.sequence)[
                    T.li(pattern="item", render=render_facet)[
                        T.slot("facetlabel"),
                        T.div(data=T.directive("tree"), render=tree.render)[
                            T.invisible(pattern="item", render=render_node)[tag, T.slot("label")]
                        ],
                    ]
                ],
            ]

            return T.invisible()[template]
示例#20
0
 def test_nested(self):
     val = []
     def appendKey(ctx, data):
         val.append(ctx.key)
         return ctx.tag
     self.render(
         tags.div(key="one", render=appendKey)[
             tags.div(key="two", render=appendKey)[
                 tags.div(render=appendKey)[
                     tags.div(key="four", render=appendKey)]]])
     self.assertEqual(val, ["one", "one.two", "one.two", "one.two.four"])
示例#21
0
    def _renderAppNav(self, tabs, template=None):
        """
        Render application navigation and return the resulting tag.

        @param template: a Tag containing a template for navigation.
        """
        if template is None:
            template = tags.span[tags.div(pattern="app-tab"), tags.div(pattern="tab-contents")]
        ctx = context.WebContext(tag=template)
        request = FakeRequest()
        ctx.remember(request)
        return webnav.applicationNavigation(ctx, FakeTranslator(), tabs)
示例#22
0
 def render_images(self, ctx, data):
     """Render a list of images.
     """
     tag = T.div(data=images, render=rend.sequence)[
         T.div(pattern='item')[
             T.p(data=T.directive('filename'), render=T.directive('data')),
             T.ul(data=T.directive('comments'), render=rend.sequence)[
                 T.li(pattern='item', render=T.directive('data')),
                 ],
             ],
         ]
     return tag
示例#23
0
 def getWidgetDocument(self):
     """
     Return part of a document which contains nodes nested several layers
     deep.  The client side of this test will use their class names to
     determine that ordering of results from the DOM traversal function is
     correct.
     """
     return tags.div(_class='container')[
         tags.div(_class='left_child')[
             tags.div(_class='left_grandchild')],
         tags.div(_class='right_child')[
             tags.div(_class='right_grandchild')]]
示例#24
0
 def tabbedPane(self, ctx, data):
     tab_names = [element[0] for element in data]
     
     return t.invisible[
     t.div(class_='tabbedPane')[
         t.ul(class_='tabs')[
             [t.li(id_="tab-"+name.replace(' ', '_'))[name] for name in tab_names]
         ],
         [t.div(id_="page-"+name.replace(' ', '_'))[fragment] for name, fragment in data]
     ],
     t.inlineJS('setupTabbedPane(['+','.join([le.flt(le.js['tab-'+name.replace(' ', '_'),'page-'+name.replace(' ', '_')], quote=False) for name, junk in data])+']);')
     ]
 def test_renderAttributeOnRenderableNestedInRenderable(self):
     """
     A L{Tag} with a renderer which returns an L{IRenderable} which renders
     to a L{Tag} with a I{render} special is replaced with the return value
     of the corresponding render method on the nested L{IRenderable}.
     """
     result = ("foo", " ", "bar")
     request = object()
     renders = []
     inner = RenderRenderable(renders, "bar", div(render="bar"), result)
     outer = RenderRenderable(renders, "foo", div(render="foo"), inner)
     self.assertStringEqual(self.flatten(outer, request), "".join(result))
     self.assertEqual(renders, [(outer, request), (inner, request)])
示例#26
0
文件: prefs.py 项目: braams/shtoom
def switcher(ctx, *args):
    """Take any number of (interface, (badgeName, headerText), body) tuples, and return html which
    will render a tabbed widget. There will be a series of tabs, which will each show a badge and some
    header text. Each tab has a body which will be shown when that tab is selected.

    interface: If the avatar cannot be adapted to the given interface, that tab will not be shown.
    badgeName: The name of an image in the /images/ directory which will be rendered
        inside of the tab.
    headerText: The text which will be rendered inside of the tab.
    body: The stan which will be shown when this tab is selected.
    """
    headers, bodies = zip(*args)
    currentView = ctx.arg('currentView', headers[0][1])
    if currentView:
        for (i, (badge, description)) in enumerate(headers):
            if description == currentView:
                currentIndex = i
                break
        else:
            raise Exception("Bad view: %s" % currentView)
    else:
        currentIndex = 0

    def genheaders():
        for i, head in enumerate(headers):
            badge, description = head
            if currentView == description:
                klas = 'tab-selected'
            else:
                klas = 'tab'

            yield T.a(href=here.add('currentView', description))[
                T.span(_class="%s" % klas)[
                    T.img(src="/images/%s.png" % badge, style="margin-right: 5px;"), description]]

    yield T.div(_class="header-line")[ genheaders() ]

    def genbodies():
        style = None
        for i, body in enumerate(bodies):
            def remember(ctx, data):
                ctx.remember([('replace', ['currentView', headers[i][1]], {})], inevow.IViewParameters)
                return ctx.tag

            if currentView != headers[i][1]:
                continue

            yield T.div(id="switch_%s" % i, style=style, render=remember)[
                body ]

    yield T.div(style="margin-top: 4px")[ genbodies() ]
示例#27
0
    def render_forms(self, ctx, data):
        forms = []

        if self.node.is_readonly():
            return T.div["No upload forms: directory is read-only"]
        if self.dirnode_children is None:
            return T.div["No upload forms: directory is unreadable"]

        mkdir = T.form(action=".", method="post",
                       enctype="multipart/form-data")[
            T.fieldset[
            T.input(type="hidden", name="t", value="mkdir"),
            T.input(type="hidden", name="when_done", value="."),
            T.legend(class_="freeform-form-label")["Create a new directory in this directory"],
            "New directory name: ",
            T.input(type="text", name="name"), " ",
            T.input(type="submit", value="Create"),
            ]]
        forms.append(T.div(class_="freeform-form")[mkdir])

        upload = T.form(action=".", method="post",
                        enctype="multipart/form-data")[
            T.fieldset[
            T.input(type="hidden", name="t", value="upload"),
            T.input(type="hidden", name="when_done", value="."),
            T.legend(class_="freeform-form-label")["Upload a file to this directory"],
            "Choose a file to upload: ",
            T.input(type="file", name="file", class_="freeform-input-file"),
            " ",
            T.input(type="submit", value="Upload"),
            " Mutable?:",
            T.input(type="checkbox", name="mutable"),
            ]]
        forms.append(T.div(class_="freeform-form")[upload])

        mount = T.form(action=".", method="post",
                        enctype="multipart/form-data")[
            T.fieldset[
            T.input(type="hidden", name="t", value="uri"),
            T.input(type="hidden", name="when_done", value="."),
            T.legend(class_="freeform-form-label")["Add a link to a file or directory which is already in Tahoe-LAFS."],
            "New child name: ",
            T.input(type="text", name="name"), " ",
            "URI of new child: ",
            T.input(type="text", name="uri"), " ",
            T.input(type="submit", value="Attach"),
            ]]
        forms.append(T.div(class_="freeform-form")[mount])
        return forms
 def test_legacyRenderer(self):
     """
     Flattening an L{IRenderer} succeeds with the same result as using the
     old flattener.
     """
     class Legacy(Fragment):
         docFactory = stan(invisible(render=directive('foo')))
         def render_foo(self, ctx, data):
             return '"&<>'
     fragment = Legacy()
     self.assertEqual(
         self.flatten(fragment), oldFlatten(fragment))
     self.assertEqual(
         self.flatten(div(foo=fragment)),
         oldFlatten(div(foo=fragment)))
 def test_renderTextDataQuoted(self):
     """
     Strings returned by a render method on an L{IRenderable} provider which
     is a child of a L{Tag} are XML quoted.
     """
     tag = div[RenderRenderable([], "foo", div(render="foo"), '"&<>')]
     self.assertStringEqual(self.flatten(tag), '<div>"&amp;&lt;&gt;</div>')
 def test_entityAttribute(self):
     """
     An instance of L{Entity} which is the value of an attribute of a L{Tag}
     is flattened to the XML representation of an arbitrary codepoint.
     """
     self.assertStringEqual(
         self.flatten(div(foo=nbsp)), '<div foo="&#160;"></div>')
示例#31
0
    def _getDescriptionHTML(self, descItem):
        """returns stan for the "description" of a service or a table.

		The RD's description is not picked up.
		"""
        iDesc = descItem.getMeta("description", propagate=False)
        if iDesc is None:
            return ""
        else:
            return T.div(class_="lidescription")[T.xml(
                iDesc.getContent("blockhtml", macroPackage=descItem))]
示例#32
0
 def test_deferredRenderAttribute(self):
     """
     Flattening an object which provides L{IRenderable} with a C{render}
     method which returns a L{Deferred} which is called back with a L{Tag}
     with a render attribute results in the return value of the named
     renderer from the L{IRenderer} which returned the L{Deferred}.
     """
     flattened = self.deferflatten(
         RenderRenderable([], "foo", succeed(div(render="foo")), "bar"))
     flattened.addCallback(self.assertStringEqual, "bar")
     return flattened
示例#33
0
 def test_deferredAttributeValueQuoting(self):
     """
     Flattening a L{Tag} which has an attribute value which is a L{Deferred}
     results in the result of the L{Deferred} being XML attribute quoted and
     included as the value for that attribute of the tag.
     """
     tag = div(foo=succeed('"&<>'))
     flattened = self.deferflatten(tag)
     flattened.addCallback(self.assertStringEqual,
                           '<div foo="&quot;&amp;&lt;&gt;"></div>')
     return flattened
示例#34
0
 def test_renderAttributeNestedInList(self):
     """
     A L{Tag} with a renderer which is in a list which is returned by
     L{IRenderable.render} is replaced with the result of the named renderer
     on the L{IRenderable} which returned the list.
     """
     result = ("foo", " ", "bar")
     renders = []
     renderable = RenderRenderable(renders, "foo", [div(render="foo")],
                                   result)
     self.assertStringEqual(self.flatten(renderable, None), "".join(result))
示例#35
0
 def test_legacySerializableReturnsSlot(self):
     """
     A slot returned by a flattener registered with L{registerFlattener} is
     filled with the value of a slot from "outside" the L{ISerializable}.
     """
     request = FakeRequest()
     result = slot('foo')
     serializable = LegacySerializable(result)
     tag = div(foo=serializable)
     tag.fillSlots("foo", "bar")
     self.assertEqual(self.flatten(tag, request), '<div foo="bar"></div>')
示例#36
0
 def getWidgetDocument(self):
     """
     Return part of a document which contains some explicitly sized
     elements.  The client portion of this test will retrieve them by their
     class value and assert things about their size.
     """
     return tags.div[
         tags.div(class_='foo', style='height: 126px; width: 1px'),
         tags.
         div(class_='bar',
             style='padding: 1px 2px 3px 4px; height: 12px; width: 70px')]
示例#37
0
 def test_authenticatedAuthenticateLinks(self):
     """
     The I{authenticateLinks} renderer should remove the tag it is passed
     from the output if it is called on a L{_PublicPageMixin} being rendered
     for an authenticated user.
     """
     page = self.createPage(self.username)
     authenticateLinksPattern = div()
     ctx = context.WebContext(tag=authenticateLinksPattern)
     tag = page.render_authenticateLinks(ctx, None)
     self.assertEqual(tag, '')
示例#38
0
 def test_authenticatedLogout(self):
     """
     The I{logout} renderer should return the tag it is passed if it is
     called on a L{_PublicPageMixin} being rendered for an authenticated
     user.
     """
     page = self.createPage(self.username)
     logoutPattern = div()
     ctx = context.WebContext(tag=logoutPattern)
     tag = page.render_logout(ctx, None)
     self.assertIdentical(logoutPattern, tag)
示例#39
0
class HistoryPage(rend.Page):
    def __init__(self, root, ob, rev):
        self.root = root
        self.ob = ob
        self.rev = rev

    def render_title(self, context, data):
        return context.tag[u"History of \N{LEFT DOUBLE QUOTATION MARK}" +
                           self.ob.fullName() +
                           u"\N{RIGHT DOUBLE QUOTATION MARK}s docstring"]

    def render_links(self, context, data):
        ds = self.root.edits(self.ob)
        therange = range(len(ds))
        rev = therange[self.rev]
        ul = tags.ul()
        for i in therange:
            li = tags.li()
            if i:
                li[tags.a(href=url.URL.fromContext(
                    context).sibling('diff').add('ob', self.ob.fullName()).add(
                        'revA', i - 1).add('revB', i))["(diff)"]]
            else:
                li["(diff)"]
            li[" - "]
            if i == len(ds) - 1:
                label = "Latest"
            else:
                label = str(i)
            if i == rev:
                li[label]
            else:
                li[tags.a(href=url.gethere.replace('rev', str(i)))[label]]
            li[' - ' + ds[i].user + '/' + ds[i].time]
            ul[li]
        return context.tag[ul]

    def render_docstring(self, context, data):
        docstring = self.root.editsbyob[self.ob][self.rev].newDocstring
        if docstring is None:
            docstring = ''
        return epydoc2stan.doc2html(self.ob, docstring=docstring)[0]

    def render_linkback(self, context, data):
        return util.taglink(self.ob, label="Back")

    docFactory = loaders.stan(
        tags.html[tags.head[
            tags.title(render=tags.directive('title')),
            tags.link(rel="stylesheet", type="text/css", href='apidocs.css')],
                  tags.body[tags.h1(render=tags.directive('title')),
                            tags.p(render=tags.directive('links')),
                            tags.div(render=tags.directive('docstring')),
                            tags.p(render=tags.directive('linkback'))]])
示例#40
0
文件: Dashboard.py 项目: calston/tums
        def ret(p):
            service = {
                'dhcpd3': ('DHCP server', 'dhcp3-server'),
                'squid': ('Web proxy', 'squid'),
                'openvpn': ('VPN server', 'openvpn'),
                'exim4': ('Mail server', 'exim4'),
                'smbd': ('File server', 'samba'),
                'sshd': ('Secure shell', 'sshd'),
            }

            slist = []

            s_red = "color:#bf0000; margin-left: 1em; margin-right: 2em"
            s_green = "color:#006b33; margin-left: 1em; margin-right: 2em"
            for k, v in service.items():
                status = p[k]
                name, init = v

                slist.append([
                    status and tags.img(src="/images/state-running.png")
                    or tags.img(src="/images/state-stopped-whitebg.png"),
                    [entities.nbsp,
                     name], status and tags.div(style=s_green)["Running"]
                    or tags.div(style=s_red)["Stopped"],
                    [
                        tags.
                        a(href="/auth/Proc/%s/start/" % init,
                          onclick=
                          "return confirm('Are you sure you want to start the %s service?');"
                          % name)[tags.img(src='/images/service-start.png')],
                        entities.nbsp, entities.nbsp, entities.nbsp,
                        tags.
                        a(href="/auth/Proc/%s/stop/" % init,
                          onclick=
                          "return confirm('Are you sure you want to stop the %s service?');"
                          % name)[tags.img(src='/images/service-stop.png')]
                    ]
                ])

            # Produce our trs
            return ctx.tag[[tags.tr[[tags.td[j] for j in i]] for i in slist]]
示例#41
0
文件: Reports.py 项目: calston/tums
    def sideMenu(self, avatarId):
        if (not avatarId.isAdmin) and avatarId.reports:
            # show a simpler menu
            # XXX Clean up this and generalise it better 
            self.sideMenuItems = [
                (url.root.child("DiskUsage"), "display", "View disk utilisation", "Disk Usage"),
                (url.root.child("Mail"), "display", "Mail logs", "Mail logs"),
                (url.root.child('Overview'), 'display', "A general overview and statistics", 'Month Overview'),
                (url.root.child("NetworkStats"), "display", "Network utilisation statistics", 'Network Utilisation'),
                (url.root.child("ProxyUse"), "display", "Reports on pages accessed through the web proxy", 'Web Proxy Usage Reporting'),
            ]

        return tags.div(id="sideCont")[
            [
                tags.div(_class="sideMenuPrimary")[
                    tags.div(_class="sideMenuNames")[
                        tags.a(_class="MenuOptionLink", href=item[0], title = item[2], onclick="showElement('loading');")[item[3]]
                    ]
                ]
            for item in self.sideMenuItems]
        ]
示例#42
0
文件: json.py 项目: calston/tums
def _serialize(obj, w, seen):
    from nevow import athena

    if isinstance(obj, types.BooleanType):
        if obj:
            w('true')
        else:
            w('false')
    elif isinstance(obj, (int, long, float)):
        w(str(obj))
    elif isinstance(obj, unicode):
        w('"')
        w(stringEncode(obj))
        w('"')
    elif isinstance(obj, types.NoneType):
        w('null')
    elif id(obj) in seen:
        raise CycleError(type(obj))
    elif isinstance(obj, (tuple, list)):
        w('[')
        for n, e in enumerate(obj):
            _serialize(e, w, seen)
            if n != len(obj) - 1:
                w(',')
        w(']')
    elif isinstance(obj, dict):
        w('{')
        for n, (k, v) in enumerate(obj.iteritems()):
            _serialize(k, w, seen)
            w(':')
            _serialize(v, w, seen)
            if n != len(obj) - 1:
                w(',')
        w('}')
    elif isinstance(obj, (athena.LiveFragment, athena.LiveElement)):
        _serialize(obj._structured(), w, seen)
    elif isinstance(obj, (rend.Fragment, page.Element)):
        wrapper = tags.div(xmlns="http://www.w3.org/1999/xhtml")
        w('"')
        w(stringEncode(flat.flatten(wrapper[obj]).decode('utf-8')))
        w('"')
    else:
        transportable = IAthenaTransportable(obj, None)
        if transportable is not None:
            w('(new ' + transportable.jsClass.encode('ascii') + '(')
            arguments = transportable.getInitialArguments()
            for n, e in enumerate(arguments):
                _serialize(e, w, seen)
                if n != len(arguments) - 1:
                    w(',')
            w('))')
        else:
            raise TypeError("Unsupported type %r: %r" % (type(obj), obj))
示例#43
0
class IDWidget(athena.LiveElement):
    jsClass = u'ControllerModule.IDWidget'
    
    docFactory = loaders.stan([tags.div(render=tags.directive('liveElement'))[
        tags.div(id="idlist")]])
    
    def __init__(self, controller):
        self.controller = controller
        reactor.callLater(1, self.ready)
        n = results.notifierFromFunction(
            lambda _:self.controller.getIDs().addCallback(self.gotIDs))
        self.controller.addNotifier(n)
    
    def ready(self):
        return self.controller.getIDs().addCallback(self.gotIDs)
        
    def gotIDs(self, idlist):
        s = ''
        for id in idlist:
            s += " <a href='monitor?ids=%i')>:%i:</a> " %(id, id)
        return self.callRemote('drawIDs', unicode(s))
示例#44
0
 def _getMessageElement(self, ctx):
     errors = []
     formErrors = iformal.IFormErrors(ctx, None)
     if formErrors is not None:
         for field in self.multiField.items:
             err = formErrors.getFieldError(field.key)
             if err is not None:
                 errors.append(err.message)
     if errors:
         return T.div(class_='message')["; ".join(errors)]
     else:
         return ''
示例#45
0
 def test_renderAttributeNestedInTag(self):
     """
     A L{Tag} with a renderer which is a child of a L{Tag} which was
     returned by L{IRenderable.render} is replaced with the result of the
     named renderer on the L{IRenderable} which returned the L{Tag}.
     """
     result = "quux"
     renders = []
     tag = div[div(render="foo")]
     renderable = RenderRenderable(renders, "foo", tag, result)
     self.assertStringEqual(self.flatten(renderable, None),
                            "<div>quux</div>")
示例#46
0
 def test_blogView(self):
     """
     L{hyperbola_view.BlogBlurbViewer.view} should render a pattern
     indicating that there are no blog posts, if it has no children.
     """
     blogShare = self._shareAndGetProxy(self._makeBlurb(FLAVOR.BLOG))
     fragment = hyperbola_view.BlogBlurbViewer(blogShare)
     tag = tags.div(pattern="no-child-blurbs", id="correct")
     result = fragment.view(FakeRequest(), tag)
     self.assertEqual(result.attributes['id'], "correct")
     self.assertEqual(
         result.slotData['child-type-name'], fragment._childTypeName)
示例#47
0
文件: runner.py 项目: msdemlei/nevow
class TestRunner(TestSuiteFragment):
    jsClass = u'Nevow.Athena.Test.TestRunner'
    docFactory = loaders.stan(
        tags.div(_class='test-runner', render=tags.directive('liveFragment'))
        [tags.form(action='#')[
            athena.handler(event='onsubmit', handler='runWithDefaults'),
            tags.input(type='submit', value='Run Tests')],
         tags.div[tags.div[tags.div['Tests passed: ',
                                    tags.span(_class='test-success-count')[0]],
                           tags.div['Tests failed: ',
                                    tags.span(_class='test-failure-count')[0]],
                           tags.div['Tests completed in: ',
                                    tags.span(_class='test-time')['-']],
                           tags.div(render=tags.directive('debug'))], tags.hr,
                  tags.div[tags.span(_class='test-results')], tags.hr,
                  tags.div(render=tags.directive('tests'))]])

    def render_debug(self, ctx, data):
        f = athena.IntrospectionFragment()
        f.setFragmentParent(self)
        return f
示例#48
0
文件: prefs.py 项目: xregist/shtoom
    def genbodies():
        style = None
        for i, body in enumerate(bodies):
            def remember(ctx, data):
                ctx.remember([('replace', ['currentView', headers[i][1]], {})], inevow.IViewParameters)
                return ctx.tag

            if currentView != headers[i][1]:
                continue

            yield T.div(id="switch_%s" % i, style=style, render=remember)[
                body ]
示例#49
0
class ChildFragment(athena.LiveFragment):
    jsClass = u'Nevow.Athena.Tests.ChildParentRelationshipTest'

    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveFragment'))[tags.div(
            render=tags.directive('childrenWidgets')), 'child'])

    def __init__(self, page, childCount):
        super(ChildFragment, self).__init__()
        self.page = page
        self.childCount = childCount

    def render_childrenWidgets(self, ctx, data):
        # yield tags.div['There are ', self.childCount, 'children']
        for i in xrange(self.childCount):
            yield ChildFragment(self.page, self.childCount - 1)

    def getChildCount(self):
        return self.childCount

    expose(getChildCount)
示例#50
0
class ResultWidget(athena.LiveElement):
    jsClass = u'ControllerModule.ResultWidget'
    ids = 'all'
    docFactory = loaders.stan([
        tags.div(render=tags.directive('liveElement'))[tags.div(
            id="resultIdDiv")[tags.input(type='text',
                                         align='center',
                                         id="resultIdField",
                                         onChange="""
            w = Nevow.Athena.Widget.get(this);
            w.callRemote('setIDs', this.value);""")]],
        tags.div(id="resultOut")
    ])

    def __init__(self):
        reactor.callLater(.1, self.callRemote, 'getIDs')

    def validResult(self, result):
        if isinstance(result, Failure):
            return True
        if isinstance(result, tuple) and len(result) is 5:
            for i in result[:2]:
                if not isinstance(i, int):
                    return False
            for s in result[2:]:
                if not isinstance(s, str):
                    return False
            if self.ids == 'all' or result[0] in self.ids:
                return True

    def handleResult(self, result):
        if not self.validResult(result):
            return
        s = resultToHTML(result)
        return self.callRemote('handleResult', unicode(s))

    def setIDs(self, ids):
        self.ids = parseTargets(ids)

    athena.expose(setIDs)
示例#51
0
    def render_fullList(self, ctx, data):
        """Render all the info for a list entry."""
        # pylint: disable-msg=E1101
        title = data.title or T.em[u'(Pas de titre)']

        if data.res:
            if data.res:
                owner, _, email = data.res
                if owner:
                    if email:
                        res = u'Réservé par ' + email
                    else:
                        res = u'Réservé'
                else:
                    res = u'Réservé'
            img = self.theme().render_Lock(ctx, res)
        else:
            img = ''

        score = self._make_score(data.score)

        # pylint: disable-msg=E1101
        if data.url:
            link = data.url
            if len(link) > 50:
                link = link[:50] + '...'
            link = T.div(style="padding-top: 1ex")[
                u'» Voir\xa0: ',
                T.a(href=data.url, target='_blank')[link]]
        else:
            link = ''

        if data.description:
            desc = format.format_description(data.description)
        else:
            desc = T.em[u'(pas de description)']

        return ctx.tag[T.h2[img, title,
                            T.span(style="padding-left:1ex")[score]],
                       T.div(_class="itemdesc")[desc, link]]
示例#52
0
 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
示例#53
0
文件: failure.py 项目: schwabe/nevow
def htmlDict(d):
    return t.div(_class="dict")[
        t.span(_class="heading")[
            "Dictionary instance @ 0x%x" % id(d)
        ],
        t.table(_class="dict")[[
            t.tr[
                t.td(_class="dictKey")[ k == '__builtins__' and 'builtin dictionary' or htmlrepr(k) ],
                t.td(_class="dictValue")[ htmlrepr(v) ]
            ]
            for k, v in list(d.items())
        ]]
    ]
示例#54
0
 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('&nbsp;'),
             tags.div(_class=self.collapsed)[self.body])
示例#55
0
class NodeLocationSubElement1(LiveElement):
    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))[
            tags.invisible(render=tags.directive('bar')),
            tags.label(_class='foo', _for="username"),
            tags.input(_class='foo', id='username')])

    def bar(self, req, tag):
        e = NodeLocationSubElement2()
        e.setFragmentParent(self)
        return e

    renderer(bar)
示例#56
0
        def makeTick(startSec, endSec, state, style='', class_=''):
            widthSec = (endSec - startSec)
            color = dict(Off='#555', On='#ffa', Suspend='#775',
                         Standby='#dca').get(state)
            if color is not None:
                color = 'background: %s; ' % color
            else:
                color = ''

            return T.div(class_="abs %s" % class_,
                         style="%s left: %.2f%%; width: %.2f%%; %s" %
                         (color, 100 * startSec / 86400,
                          100 * widthSec / 86400, style))[state]
示例#57
0
    def calculateDefaultSkin(self, context):
        if self.isGrouped:
            frm = tags.invisible
            butt = ''
            fld = tags.invisible
        else:
            frm = tags.form(id=slot('form-id'),
                            name=slot('form-id'),
                            action=slot('form-action'),
                            method="post",
                            enctype="multipart/form-data",
                            **{'accept-charset': 'utf-8'})
            butt = slot('form-button')
            fld = tags.fieldset[tags.input(type='hidden', name='_charset_')]

        ## Provide default skin since no skin was provided for us.
        context.tag.clear()[frm[fld[
            tags.legend(_class="freeform-form-label")[slot('form-label')],
            tags.div(
                _class="freeform-form-description")[slot('form-description')],
            tags.div(_class="freeform-form-error")[slot('form-error')],
            slot('form-arguments'), butt]]]
示例#58
0
    def render_listDesc(self, ctx, _):
        """Render the list's description."""
        avatar = maybe_user(ctx)
        editable = manages_list(ctx, avatar, self.list)

        # pylint: disable-msg=E1101
        desc = self.list.desc or T.em['(pas de description)']

        if editable:
            invite = url.URL.fromString("/invite")
            invite = invite.add('lst', str(self.list.id))

            srv = IService(ctx)
            name = self.list.name or 'ma liste'

            action = """
            url=encodeURIComponent(location.href);location.href='%s?url='+url+'&title='+encodeURIComponent(document.title)+'&back='+url
            """ % (srv.base_url + '/' + self.list.url)
            action = re.sub('\s+', ' ', action.strip())
            desc = [
                desc,
                T.div(_class="listaction")[
                    u'» ', T.b[T.a(href=invite)[u'Inviter']], ' :: ',
                    T.a(href=url.here.child('edit'))[u'Modifier'], ' :: ',
                    T.a(href=url.here.child('destroy'))[u'Détruire'], ],
                T.div(_class="listaction")[
                    T.em[u'Glisse moi dans tes bookmarks\xa0! '],
                    T.a(href='javascript:' + action)[u'» %s' % name]]
            ]
        elif avatar.identified:
            desc = [
                desc,
                T.div(_class="listaction")[
                    u'» ',
                    T.a(href=url.here.child('unsubscribe'))[u'Ignorer'], ]
            ]

        return ctx.tag[desc]
示例#59
0
def mapHtml():
    width = 600
    height = 900

    dots = []
    for measurement in UpdatingMeasurements().measurements:
        try:
            speed = float(measurement['speed'])
        except ValueError:
            print "no speed", measurement
            continue
        color = "#%02x%02x%02x" % (interp(
            speed, 50, 0, 0, 255), interp(speed, 40, 80, 0, 255), 0)

        pos = (interp(float(measurement['longitude']), -122.72, -121.50, 0,
                      width),
               interp(float(measurement['latitude']), 38.41, 36.93, 0, height))

        dotText = u'\u2739'
        if random.random() > .9:
            dotText += ' %d' % speed
        dots.append(
            T.div(
                style="color: %s; position: absolute; left: %spx; top: %spx" %
                (color, pos[0], pos[1]))[dotText])

    page = [
        T.raw('''<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'''),
        T.html(xmlns="http://www.w3.org/1999/xhtml")[T.head[T.style[T.raw('''
        * {
        font-size: 90%;
        }
        ''')]], T.body[T.div(style="width: %spx; height: %spx" %
                             (width, height))[dots]]]
    ]
    return flat.flatten(page)
示例#60
0
文件: guarded2.py 项目: schwabe/nevow
class MyPage(rend.Page):
    addSlash = True
    docFactory = loaders.stan(
    tags.html[
        tags.head[tags.title["Hi Boy"]],
        tags.body[
            tags.invisible(render=tags.directive("isLogged"))[
                tags.div(pattern="False")[
                    tags.form(action=guard.LOGIN_AVATAR, method='post')[
                        tags.table[
                            tags.tr[
                                tags.td[ "Username:"******"Password:"******"True")[
                    tags.h3["Hi bro"],
                    tags.invisible(render=tags.directive("sessionId")),
                    tags.br,
                    tags.a(href=guard.LOGOUT_AVATAR)["Logout"]
                ]
            ]
        ]
    ])
 
    def __init__(self, avatarId=None):
        rend.Page.__init__(self)
        self.avatarId=avatarId
 
    def render_isLogged(self, context, data):
        q = inevow.IQ(context)
        true_pattern = q.onePattern('True')
        false_pattern = q.onePattern('False')
        if self.avatarId: return true_pattern or context.tag().clear()
        else: return false_pattern or context.tag().clear()
 
    def render_sessionId(self, context, data):
        sess = inevow.ISession(context)
        return context.tag[sess.uid]
 
    def logout(self):
        print("Bye")