Esempio n. 1
0
class DBItem(rend.Page):
    implements(IItemWithSubject)
    addSlash = True

    def setSubject(self, newSubject):
        ## Self.original is the data that was passed to the DBItem constructor above; the id of this record
        doQuery('update foo set subject = "%s" where id = %s', newSubject,
                self.original)

    def render_viewSelector(self, context, data):
        args = inevow.IRequest(context).args
        view = args.get('view', ['view'])[0]
        if view == 'view':
            selector = "View | ", tags.a(href=here.add('view', 'edit'))["Edit"]
            editor = ''
        else:
            selector = tags.a(href=here.add('view', 'view'))["View"], " | Edit"
            editor = context.onePattern(
                'edit')()  # get one copy of the edit pattern
        viewer = context.onePattern(
            'view')()  # get one copy of the view pattern
        return selector, viewer, editor

    def render_itemDetail(self, context, data):
        theId, theSubject = doQuery('select * from foo where id = %s',
                                    self.original)[0]
        return tags.h2["Object ", theId], tags.span["Subject: ", theSubject]

    docFactory = loaders.stan(
        tags.html[tags.body[tags.p[tags.a(href=here.parent())["Up"]],
                            tags.div(render=render_viewSelector)[
                                tags.p(pattern="edit")[webform.renderForms()],
                                tags.p(pattern="view")[render_itemDetail]]]])
Esempio n. 2
0
        def gotSize(size):
            quality = ctx.arg('quality')
            large = ctx.arg('large',None)
            if large is not None:            
                size = 'size=968x1200&'
                quality='100'
            else:
                size = 'size=600x632&'
            if quality is None:
                quality = '&quality=60'
                linkhref='?quality=93'
                enhance=T.p(class_='enhance')['click to enhance']
            else:
                quality = '&quality=100'
                linkhref='?large=True'
                enhance = T.p(class_='enhance')['click to see larger']

            if large is not None:
                enhance = T.p(class_='enhance')['click to return to small view']
                linkhref='?quality=93'
                
                
            if common.isInverted(ctx) is True:
                invert='&invert=inverted'
            else:
                invert=''
            imgsrc='/system/ecommerce/%s/mainImage?%ssharpen=1.0x0.5%%2b0.8%%2b0.1%s%s'%(self.photo.id,size,quality,invert)
            html = T.a(class_='photo',href=linkhref)[ enhance,T.img(src=imgsrc) ]
            return html
Esempio n. 3
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'))]])
def renderOnce(fragmentClass):
    """
    Create L{DEPTH} LiveFragments, each nested within the next, and then render
    the result.
    """
    rname = fragmentClass.__name__[0].lower() + fragmentClass.__name__[1:]
    innerFragment = fragmentClass(docFactory=stan(p(render=directive(rname))["Hello, world."]))
    for i in xrange(DEPTH - 1):
        outerFragment = fragmentClass(docFactory=stan(p(render=directive(rname))[innerFragment]))
        innerFragment.setFragmentParent(outerFragment)
        innerFragment = outerFragment
    render(outerFragment)
Esempio n. 5
0
	def data_login_form(self, ctx, data):
		if(self.user):
			result = tags.p()[
				"You have been successfully logged in as %s" % self.user.username
			]
		else:
			result = tags.form(method="POST")[[
				tags.p()['Enter your OpenID identifier to login:'],
				tags.label(_for="openid-field")["id:"],
				tags.input(type="text", size="60", name="identity"),
				tags.input(type="submit", name="submit", value="login"),
			]]
		return result
Esempio n. 6
0
def renderOnce(fragmentClass):
    """
    Create L{DEPTH} LiveFragments, each nested within the next, and then render
    the result.
    """
    rname = fragmentClass.__name__[0].lower() + fragmentClass.__name__[1:]
    innerFragment = fragmentClass(
        docFactory=stan(p(render=directive(rname))['Hello, world.']))
    for i in xrange(DEPTH - 1):
        outerFragment = fragmentClass(
            docFactory=stan(p(render=directive(rname))[innerFragment]))
        innerFragment.setFragmentParent(outerFragment)
        innerFragment = outerFragment
    render(outerFragment)
Esempio n. 7
0
        class Page(rend.Page):
            docFactory = loaders.stan(
                html(render=directive("template"))[body[
                    p(render=directive("before")), p[slot(name="maincontent")],
                    p(render=directive("after")), ], ])

            def render_before(self, context, data):
                return context.tag["before"]

            def render_template(self, context, data):
                context.fillSlots('maincontent', Fragment())
                return context.tag

            def render_after(self, context, data):
                return context.tag["after"]
class LivePageRendererTestCase(TestCase):
    """
    Test utility function L{render} to make sure it can render various kinds of
    fragments.
    """

    message = 'Hello, world.'
    docFactory = stan(p(render=directive('liveElement'))[message])

    def testRenderLiveFragment(self):
        """
        Test that L{render} spits out the right thing for a L{LiveFragment}.
        """
        self.assertIn(
            self.message,
            render(LiveFragment(docFactory=self.docFactory)))


    def testRenderLiveElement(self):
        """
        Test that L{render} spits out the right thing for a L{LiveElement}.
        """
        self.assertIn(
            self.message,
            render(LiveElement(docFactory=self.docFactory)))
Esempio n. 9
0
class FormExamplePage(formal.ResourceMixin, rend.Page):
    """
    A base page for the actual examples. The page renders something sensible,
    including the title example and description. It also include the "example"
    form in an appropriate place.
    
    Each example page is expected to provide the title and description
    attributes as well as a form_example method that builds and returns a
    formal.Form instance.
    """
    docFactory = loaders.stan(
        T.invisible[DOCTYPE, T.html[
            T.head[CHARSET,
                   T.title(data=T.directive('title'), render=rend.data),
                   T.link(rel='stylesheet',
                          type='text/css',
                          href=url.root.child('examples.css')),
                   T.link(rel='stylesheet',
                          type='text/css',
                          href=url.root.child('formal.css')),
                   T.script(type='text/javascript', src='js/formal.js'), ],
            T.body[T.h1(data=T.directive('title'), render=rend.data),
                   T.p(data=T.directive('description'), render=rend.data),
                   T.directive('form example'), ], ], ], )

    def data_title(self, ctx, data):
        return self.title

    def data_description(self, ctx, data):
        return self.description
Esempio n. 10
0
class Uploader(formrender.Form):
	"""A renderer allowing for updates to individual records using file upload.

	This renderer exposes a form with a file widget.	It is likely that
	the interface will change.
	"""

	name = "upload"

	def render_uploadInfo(self, ctx, data):
		if data is None:
			return T.invisible()
		else:
			for key, val in data.original.getPrimaryTable().rows[0].iteritems():
				ctx.tag.fillSlots(key, str(val))
			return ctx.tag

	docFactory = loaders.stan(T.html[
		T.head[
			T.title["Upload"],
			T.invisible(render=T.directive("commonhead")),
		],
		T.body(render=T.directive("withsidebar"))[
			T.h1(render=T.directive("meta"))["title"],
			T.p(class_="procMessage", data=T.directive("result"), 
					render=T.directive("uploadInfo"))[
				T.slot(name="nAffected"),
				" record(s) modified."
			],
			T.invisible(render=T.directive("form genForm"))
		]
	])
Esempio n. 11
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']
             ]
     ]
Esempio n. 12
0
 def render_section(self, ctx, data):
     link = url.root.child('section').child(data['sid'])
     ctx.tag.fillSlots('title', t.a(href=link)[data['stitle']])
     ctx.tag.fillSlots('thread_num', data['thread_num'])
     ctx.tag.fillSlots('description', t.p(_class="desc")[data['sdescription']])
     ctx.tag.fillSlots('lastMod', pptime(data['lastmod']))
     return ctx.tag
Esempio n. 13
0
 def test_dataContextCreation(self):
     data = {'foo': 'oof', 'bar': 'rab'}
     doc = tags.p(data=data)[tags.slot('foo'), tags.slot('bar')]
     doc.fillSlots('foo',
                   tags.invisible(data=tags.directive('foo'), render=str))
     doc.fillSlots('bar', lambda ctx, data: data['bar'])
     self.assertEquals(flat.flatten(doc), '<p>oofrab</p>')
Esempio n. 14
0
 class Page2(Base):
     docFactory = loaders.stan(
         html[
             body[
                 p(macro=directive('content'))
             ]
         ])
Esempio n. 15
0
    def test_stanDirectiveRendering(self):
        """
        Test that a Element with a valid render directive has that directive
        invoked and the result added to the output.
        """
        renders = []

        class RenderfulElement(Element):
            def renderMethod(self, request, tag):
                renders.append((self, request))
                return tag["Hello, world."]

            renderer(renderMethod)

        request = object()
        element = RenderfulElement(
            docFactory=stan(p(render=directive('renderMethod'))))
        finished = self._render(element, request)

        def cbFinished(result):
            self.assertEqual(result, "<p>Hello, world.</p>")
            self.assertEqual(renders, [(element, request)])

        finished.addCallback(cbFinished)
        return finished
Esempio n. 16
0
	def render_rdlink(self, ctx, data):
		if hasattr(self.failure.value, "rd") and self.failure.value.rd:
			rdURL = base.makeAbsoluteURL("/browse/%s"%
				self.failure.value.rd.sourceId)
			return T.p(class_="rdbacklink")["Also see the ",
				T.a(href=rdURL)["resources provided by this RD"],
				"."]
		return ""
Esempio n. 17
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
Esempio n. 18
0
class Root(rend.Page):
    implements(ITodo)
    
    child_css = webform.defaultCSS
    
    docFactory = loaders.stan(
        t.html(render=t.directive("time"))[
            t.head[
                t.title['todo'],
                t.style(type="text/css")[".done { color: #dddddd; }"],
                t.style(type="text/css")["@import url(/css);"]
                ],
            t.body[
                webform.renderForms(),
                t.ul(data=t.directive("findAll"),
                     render=t.directive("sequence"))[
                         t.li(pattern="item",render=t.directive('todo')),
                         t.li(pattern="empty",render=t.directive('empty')),
                ],
                t.p(render=t.directive("end"))
            ]
        ]
    )
    
    def insert(self, ctx, description):
        return itodo.ITodos(ctx).add(description, 0)
    
    def delete(self, ctx, id):
        return itodo.ITodos(ctx).delete(id)

    def update(self, ctx, id, oldstate):
        newstate = [1, 0][oldstate]
        return itodo.ITodos(ctx).update(id, newstate)
        
    def data_findAll(self, ctx, data):
        return itodo.ITodos(ctx).findAll()

    def render_todo(self, ctx, data):
        deluri = "freeform_post!!delete?id="+str(data[0])
        updateuri = "freeform_post!!update?id="+str(data[0])+"&oldstate="+str(data[2])
        state = [" Done", " To Do"][int(data[2])==0]
        tag = ctx.tag
        if data[2]:
            tag = ctx.tag(_class="done")
        return tag[data[1]+" - ",
                   t.a(href=deluri)["Delete"], " / ",
                   t.a(href=updateuri)[("Mark Done", "Mark Undone")[data[2]]],
                   state]

    def render_empty(self, ctx, data):
        return ctx.tag["No Todos"]
    
    def render_time(self, ctx, data):
        ctx.remember(now(), itodo.ITimer)
        return ctx.tag
        
    def render_end(self, ctx, data):
        return ctx.tag["%.3f"%(now()-itodo.ITimer(ctx))]
Esempio n. 19
0
        class Page(rend.Page):
            docFactory = loaders.stan(html[body[p(data=directive('foo'),
                                                  render=directive('bar'))]])

            def data_foo(self, ctx, data):
                return 'foo'

            def render_bar(self, ctx, data):
                return ctx.tag.clear()[data + 'bar']
Esempio n. 20
0
 def test_precompileWithRenderer(self):
     tag = tags.html[tags.body[tags.div[tags.p["Here's a string"],
                                        tags.p(data=5, render=str)]]]
     prelude, context, postlude = self.render(tag, precompile=True)
     self.assertEquals(prelude, "<html><body><div><p>Here's a string</p>")
     self.assertEquals(context.tag.tagName, "p")
     self.assertEquals(context.tag.data, 5)
     self.assertEquals(context.tag.render, str)
     self.assertEquals(postlude, '</div></body></html>')
Esempio n. 21
0
    def test_data(self):
        ctx = context.WovenContext()

        ctx.remember('foo', inevow.IData)
        tag = p(render=rend.data)
        self.assertEqual(flat.flatten(tag, ctx), '<p>foo</p>')

        ctx.remember('\xc2\xa3'.decode('utf-8'), inevow.IData)
        tag = p(render=rend.data)
        self.assertEqual(flat.flatten(tag, ctx), '<p>\xc2\xa3</p>')

        ctx.remember([1, 2, 3, 4, 5], inevow.IData)
        tag = p(render=rend.data)
        self.assertEqual(flat.flatten(tag, ctx), '<p>12345</p>')

        ctx.remember({'foo': 'bar'}, inevow.IData)
        tag = p(data=directive('foo'), render=rend.data)
        self.assertEqual(flat.flatten(tag, ctx), '<p>bar</p>')
    def test_data(self):
        ctx = context.WovenContext()

        ctx.remember('foo', inevow.IData)
        tag = p(render=rend.data)
        self.assertEquals(flat.flatten(tag, ctx), '<p>foo</p>')

        ctx.remember('\xc2\xa3'.decode('utf-8'), inevow.IData)
        tag = p(render=rend.data)
        self.assertEquals(flat.flatten(tag, ctx), '<p>\xc2\xa3</p>')

        ctx.remember([1,2,3,4,5], inevow.IData)
        tag = p(render=rend.data)
        self.assertEquals(flat.flatten(tag, ctx), '<p>12345</p>')

        ctx.remember({'foo':'bar'}, inevow.IData)
        tag = p(data=directive('foo'), render=rend.data)
        self.assertEquals(flat.flatten(tag, ctx), '<p>bar</p>')
Esempio n. 23
0
	def data_info(self, ctx, data):
		"""
		Template function to display basic user info.
		"""
		return tags.p()[
			"authorization information for %s (username '%s')." % (
				self.user['first'] + ' ' + self.user['last'],
				self.user['username'],
			)
		]
Esempio n. 24
0
class ErrorDisplay(ErrorPage):
	handles = base.ReportableError
	status = 500
	titleMessage = "Server Failure"
	beforeMessage = ("An unexpected Problem occurred:")
	afterMessage = [T.p["This usually means we've fouled up, and there's no"
				" telling whether we've realized that already.  So, chances are"
				" we'd be grateful if you told us at the address given below."
				" Thanks."],
			T.p(render=T.directive("hint"))]
Esempio n. 25
0
 class Page1(Base):
     docFactory = loaders.stan(
         html[
             body(render=directive('foo'))[
                 p(macro=directive('content'))
             ]
         ])
         
     def render_foo(self, ctx, data):
         return ctx.tag
        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]
Esempio n. 27
0
 def render_section(self, ctx, data):
     link = url.root.clear().child('section').child(data['sid']).child('')
     if data['lastmod']: tm = pptime(data['lastmod'])
     else: tm = "-"
     if data['thread_num']: n = data['thread_num']
     else: n = "0"
     ctx.tag.fillSlots('title', t.a(href=link)[data['stitle']])        
     ctx.tag.fillSlots('thread_num', n)
     ctx.tag.fillSlots('description', t.p(_class="desc")[data['sdescription']])
     ctx.tag.fillSlots('lastMod', tm)
     return ctx.tag
Esempio n. 28
0
 def render_news(self, ctx, data):
     markup = []
     append = markup.append
     for i in self.data['news'][:self.countItems]:
         append(T.p(_class='datetime')[i['date']])
         append(T.h3[i['title']])
         for para in i['c'].split('\n'):
             if para.strip() == '': continue
             append(self._render_para(para))
             append('\n')
     return markup
Esempio n. 29
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
Esempio n. 30
0
class ForbiddenPage(ErrorPage):
	handles = svcs.ForbiddenURI
	status = 403
	titleMessage = "Forbidden"
	beforeMessage = "We're sorry, but the resource you requested is forbidden."
	afterMessage = T.div[
		T.p["This usually means you tried to use a renderer on a service"
			" that does not support it.  If you did not come up with the"
			" URL in question yourself, complain fiercely to the staff of ",
			T.invisible(render=T.directive("getconfig"))["[web]sitename"],
			"."],
		T.p(render=T.directive("rdlink"))]
Esempio n. 31
0
 def render_preview(self, context, data):
     docstring = parse_str(self.docstring)
     stan, errors = epydoc2stan.doc2html(
         self.ob, docstring=docstring)
     if self.isPreview or errors:
         if errors:
             tag = context.tag
             #print stan, errors
             #assert isinstance(stan, tags.pre)
             [text] = stan.children
             lines = text.replace('\r\n', '\n').split('\n')
             line2err = {}
             for err in errors:
                 if isinstance(err, str):
                     ln = None
                 else:
                     ln = err.linenum()
                 line2err.setdefault(ln, []).append(err)
             w = len(str(len(lines)))
             for i, line in enumerate(lines):
                 i += 1
                 cls = "preview"
                 if i in line2err:
                     cls += " error"
                 tag[tags.pre(class_=cls)["%*s"%(w, i), ' ', line]]
                 for err in line2err.get(i, []):
                     tag[tags.p(class_="errormessage")[err.descr()]]
             i += 1
             for err in line2err.get(i, []):
                 tag[tags.p(class_="errormessage")[err.descr()]]
             items = []
             for err in line2err.get(None, []):
                 items.append(tags.li[str(err)])
             if items:
                 tag[tags.ul[items]]
         else:
             tag = context.tag[stan]
         return tag[tags.h2["Edit"]]
     else:
         return ()
Esempio n. 32
0
    def test_precompilePrecompiled(self):
        def render_same(context, data):
            return context.tag

        doc = tags.html[tags.body(
            render=render_same,
            data={'foo': 5})[tags.p["Hello"],
                             tags.p(data=tags.directive('foo'))[str]]]
        result1 = self.render(doc, precompile=True)
        result2 = self.render(result1, precompile=True)
        rendered = self.render(result2)
        self.assertEquals(rendered,
                          "<html><body><p>Hello</p><p>5</p></body></html>")
Esempio n. 33
0
 def test_elementContainingStaticElement(self):
     """
     Test that a Element which is returned by the render method of another
     Element is rendered properly.
     """
     class RenderfulElement(Element):
         def renderMethod(self, request, tag):
             return tag[Element(docFactory=stan("Hello, world."))]
         renderer(renderMethod)
     f = RenderfulElement(
         docFactory=stan(p(render=directive('renderMethod'))))
     return self._render(f).addCallback(
         self.assertEqual, "<p>Hello, world.</p>")
Esempio n. 34
0
 def test_missingRenderMethod(self):
     """
     Test that flattening an L{Element} with a C{docFactory} which has a tag
     with a render directive fails with L{FlattenerError} if there is no
     available render method to satisfy that directive.
     """
     element = Element(docFactory=stan(p(render=directive('renderMethod'))))
     def cb(ignored):
         # The old flattener unconditionally logs errors.
         self.flushLoggedErrors(MissingRenderMethod)
     d = self.assertFailure(self._render(element), FlattenerError)
     d.addCallback(cb)
     return d
Esempio n. 35
0
 def render_preview(self, context, data):
     docstring = parse_str(self.docstring)
     stan, errors = epydoc2stan.doc2html(self.ob, docstring=docstring)
     if self.isPreview or errors:
         if errors:
             tag = context.tag
             #print stan, errors
             #assert isinstance(stan, tags.pre)
             [text] = stan.children
             lines = text.replace('\r\n', '\n').split('\n')
             line2err = {}
             for err in errors:
                 if isinstance(err, str):
                     ln = None
                 else:
                     ln = err.linenum()
                 line2err.setdefault(ln, []).append(err)
             w = len(str(len(lines)))
             for i, line in enumerate(lines):
                 i += 1
                 cls = "preview"
                 if i in line2err:
                     cls += " error"
                 tag[tags.pre(class_=cls)["%*s" % (w, i), ' ', line]]
                 for err in line2err.get(i, []):
                     tag[tags.p(class_="errormessage")[err.descr()]]
             i += 1
             for err in line2err.get(i, []):
                 tag[tags.p(class_="errormessage")[err.descr()]]
             items = []
             for err in line2err.get(None, []):
                 items.append(tags.li[str(err)])
             if items:
                 tag[tags.ul[items]]
         else:
             tag = context.tag[stan]
         return tag[tags.h2["Edit"]]
     else:
         return ()
Esempio n. 36
0
 def test_stanDirectiveRenderingOmittingTag(self):
     """
     Test that a Element with a render method which omits the containing
     tag successfully removes that tag from the output.
     """
     class RenderfulElement(Element):
         def renderMethod(self, request, tag):
             return "Hello, world."
         renderer(renderMethod)
     f = RenderfulElement(
         docFactory=stan(p(render=directive('renderMethod'))[
                 "Goodbye, world."]))
     return self._render(f).addCallback(
         self.assertEqual, "Hello, world.")
Esempio n. 37
0
    def helpLister(context, data):
        ret = []
        for label, noteex, eachList in help:
            ret.append(T.h4[label.encode('utf-8')])

            for i in noteex:
                if type(i) == type("") or type(i) is unicode:
                    ret.append(T.p(class_="note")[i.encode('utf-8')])
                else:
                    ret.append(processEx(i))

            ret.append(processTable(eachList))

        return ret
Esempio n. 38
0
    def helpLister(context, data):
        ret = []
        for label, noteex, eachList in help:
            ret.append(T.h4 [ label.encode('utf-8')] )

            for i in noteex:
                if type(i) == type("") or type(i) is unicode:
                    ret.append(T.p(class_="note") [ i.encode('utf-8') ])
                else:
                    ret.append(processEx(i))

            ret.append(processTable(eachList))

        return ret
Esempio n. 39
0
    def test_stanDirectiveRenderingOmittingTag(self):
        """
        Test that a Element with a render method which omits the containing
        tag successfully removes that tag from the output.
        """
        class RenderfulElement(Element):
            def renderMethod(self, request, tag):
                return "Hello, world."

            renderer(renderMethod)

        f = RenderfulElement(docFactory=stan(
            p(render=directive('renderMethod'))["Goodbye, world."]))
        return self._render(f).addCallback(self.assertEquals, "Hello, world.")
Esempio n. 40
0
class RenderCrashPage(rend.Page):
    """A page that crashes during render.
	"""
    def render_crash(self, ctx, data):
        try:
            raise Exception("Wanton crash")
        except:
            import traceback
            traceback.print_exc()
            raise

    docFactory = common.doctypedStan(
        T.html[T.head[T.title["A page"], ], T.body[T.p(
            render=T.directive("crash"))["You should not see this"]]])
Esempio n. 41
0
 def test_oldFlattenableInAttribute(self):
     """
     Flattening a L{Element} as the value of an attribute of a L{Tag} XML
     attribute escapes the element's flattened document.
     """
     result = []
     element = Element()
     element.docFactory = stan(['"&<>'])
     request = FakeRequest()
     context = WovenContext()
     context.remember(request)
     finished = oldFlatten(p(foo=element), context, result.append, lambda ign: ign)
     finished.addCallback(lambda ign: "".join(result))
     finished.addCallback(self.assertEqual, '<p foo="&quot;&amp;&lt;&gt;"></p>')
     return finished
Esempio n. 42
0
 def test_precompilePrecompiled(self):
     def render_same(context, data):
         return context.tag
     doc = tags.html[
         tags.body(render=render_same, data={'foo':5})[
             tags.p["Hello"],
             tags.p(data=tags.directive('foo'))[
                 str
             ]
         ]
     ]
     result1 = self.render(doc, precompile=True)
     result2 = self.render(result1, precompile=True)
     rendered = self.render(result2)
     self.assertEquals(rendered, "<html><body><p>Hello</p><p>5</p></body></html>")
Esempio n. 43
0
 def test_precompileWithRenderer(self):
     tag = tags.html[
         tags.body[
             tags.div[
                 tags.p["Here's a string"],
                 tags.p(data=5, render=str)
             ]
         ]
     ]
     prelude, context, postlude = self.render(tag, precompile=True)
     self.assertEqual(prelude, "<html><body><div><p>Here's a string</p>")
     self.assertEqual(context.tag.tagName, "p")
     self.assertEqual(context.tag.data, 5)
     self.assertEqual(context.tag.render, str)
     self.assertEqual(postlude, '</div></body></html>')
Esempio n. 44
0
 def render_section(self, ctx, data):
     link = url.root.clear().child("section").child(data["sid"])
     if data["lastmod"]:
         tm = pptime(data["lastmod"])
     else:
         tm = "-"
     if data["thread_num"]:
         n = data["thread_num"]
     else:
         n = "0"
     ctx.tag.fillSlots("title", t.a(href=link)[data["stitle"]])
     ctx.tag.fillSlots("thread_num", n)
     ctx.tag.fillSlots("description", t.p(_class="desc")[data["sdescription"]])
     ctx.tag.fillSlots("lastMod", tm)
     return ctx.tag
Esempio n. 45
0
    def test_stanDirectiveRendering(self):
        """
        Test that a Element with a valid render directive has that directive
        invoked and the result added to the output.
        """
        class RenderfulElement(Element):
            def renderMethod(self, request, tag):
                return tag["Hello, world."]

            renderer(renderMethod)

        f = RenderfulElement(
            docFactory=stan(p(render=directive('renderMethod'))))
        return self._render(f).addCallback(self.assertEquals,
                                           "<p>Hello, world.</p>")
Esempio n. 46
0
    def render_editContent(self, ctx, data):
        if not self.avatarId.checkDomainPermissions(self.domain):
            return ctx.tag["Nice try"]
        if Settings.sambaDN and self.domain == Settings.defaultDomain:
            sambaGroups = tags.a(
                _class="noUnderline",
                href=url.root.child("Users").child('Groups').child(
                    self.domain).child(self.cid))[
                        tags.img(src="/images/groupsm.png", align="absmiddle"),
                        self.text.userLinkEditMembership]
            PBXTab = PBXUtils.enabled()
        else:
            sambaGroups = ""
            PBXTab = False

        notice = ""
        if self.cid == "root" and Settings.sambaDN:
            notice = tags.strong[tags.p(
                style="color:#f00")[self.text.userWarningEditRoot]]

        if self.returns == 'Completed':
            notice = tags.img(src='/images/modsuccess.png')
        elif self.returns == 'Failed':
            notice = tags.h1['Edit Failed!']

        tabs = [(self.text.userTabSettings, 'editForm-userSettings'),
                (self.text.userTabPermissions, 'editForm-userPermissions'),
                (self.text.userTabMail, 'editForm-mailSettings'),
                (self.text.userTabAccess, 'editForm-userAccess')]

        if PBXTab:
            tabs.append(
                (self.text.userFormUserExtension, 'editForm-userExtension'))
            tabs.append((self.text.userFormUserFKeys, 'editForm-userFKeys'))

        return ctx.tag[
            notice, tags.h3[self.text.userHeadingEditUser, self.cid],
            tags.a(_class="noUnderline",
                   href=url.root.child('Users').child('Delete').
                   child(str(self.domain)).child(str(self.cid)),
                   onclick="return confirm('%s');" %
                   self.text.userConfirmDelete)[
                       tags.img(src="/images/ex-wbg.png", align="absmiddle"),
                       self.text.userLinkDeleteUser], sambaGroups,
            PageHelpers.TabSwitcher(tabs),
            tags.directive('form editForm'),
            PageHelpers.LoadTabSwitcher()]
Esempio n. 47
0
    def render_magic_folder(self, ctx, data):
        if self.client._magic_folder is None:
            return T.p()

        (ok, messages) = self.client._magic_folder.get_public_status()

        if ok:
            ctx.fillSlots("magic_folder_status", "yes")
            ctx.fillSlots("magic_folder_status_alt", "working")
        else:
            ctx.fillSlots("magic_folder_status", "no")
            ctx.fillSlots("magic_folder_status_alt", "not working")

        status = T.ul()
        for msg in messages:
            status[T.li[str(msg)]]

        return ctx.tag[status]
Esempio n. 48
0
    def render_magic_folder(self, ctx, data):
        if self.client._magic_folder is None:
            return T.p()

        (ok, messages) = self.client._magic_folder.get_public_status()

        if ok:
            ctx.fillSlots("magic_folder_status", "yes")
            ctx.fillSlots("magic_folder_status_alt", "working")
        else:
            ctx.fillSlots("magic_folder_status", "no")
            ctx.fillSlots("magic_folder_status_alt", "not working")

        status = T.ul()
        for msg in messages:
            status[T.li[str(msg)]]

        return ctx.tag[status]
Esempio n. 49
0
 def test_elementContainingDynamicElement(self):
     """
     Test that directives in the document factory of a Element returned from a
     render method of another Element are satisfied from the correct object:
     the "inner" Element.
     """
     class OuterElement(Element):
         def outerMethod(self, request, tag):
             return tag[InnerElement(docFactory=stan(directive("innerMethod")))]
         renderer(outerMethod)
     class InnerElement(Element):
         def innerMethod(self, request, tag):
             return "Hello, world."
         renderer(innerMethod)
     f = OuterElement(
         docFactory=stan(p(render=directive('outerMethod'))))
     return self._render(f).addCallback(
         self.assertEqual, "<p>Hello, world.</p>")
Esempio n. 50
0
 def test_stanDirectiveRendering(self):
     """
     Test that a Element with a valid render directive has that directive
     invoked and the result added to the output.
     """
     renders = []
     class RenderfulElement(Element):
         def renderMethod(self, request, tag):
             renders.append((self, request))
             return tag["Hello, world."]
         renderer(renderMethod)
     request = object()
     element = RenderfulElement(
         docFactory=stan(p(render=directive('renderMethod'))))
     finished = self._render(element, request)
     def cbFinished(result):
         self.assertEqual(result, "<p>Hello, world.</p>")
         self.assertEqual(renders, [(element, request)])
     finished.addCallback(cbFinished)
     return finished
Esempio n. 51
0
def addOptionsFields(form, product=None, hasStock=False):
    description = ''
    if product and product.options:
        u = url.here.child('options.csv')
        description = T.p()[T.a(href=u)['Current Options CSV']]
    
    options = formal.Group('options', label='Options', description=description)
    form.add( options )
    options.add( formal.Field('optionsCSV', formal.File(), formal.FileUploadWidget))

    if product:
        for option in product.options:
            dataKey = 'options.'+option['code']
            group = formal.Group( option['code'], label=option['code'], 
                description=getOptionsStr(option) )
            options.add( group )
            group.add( formal.Field( 'price', formal.Decimal(required=True) ) )
            form.data[dataKey+'.price'] = option['price']

            if hasStock:
                group.add(formal.Field('currentLevel', formal.Integer(immutable=True)))
                form.data[dataKey+'.currentLevel'] = option['_stockLevel']
                group.add(formal.Field('adjustment', formal.Integer()))
 def test_dataRenderer(self):
     ctx = context.WovenContext()
     ctx.remember(rend.RenderFactory(), inevow.IRendererFactory)
     self.assertEquals(flat.flatten(p(data='foo', render=directive('data')), ctx), '<p>foo</p>')
Esempio n. 53
0
 def test_dataContextCreation(self):
     data = {'foo':'oof', 'bar':'rab'}
     doc = tags.p(data=data)[tags.slot('foo'), tags.slot('bar')]
     doc.fillSlots('foo', tags.invisible(data=tags.directive('foo'), render=str))
     doc.fillSlots('bar', lambda ctx,data: data['bar'])
     self.assertEqual(flat.flatten(doc), '<p>oofrab</p>')
Esempio n. 54
0
 def render_magic_folder(self, ctx, data):
     if not self.client._magic_folders:
         return T.p()
     return ctx.tag
Esempio n. 55
0
 def render_advice(self, ctx, data):
     return ctx.tag[
         t.p["This counter has been called:"],
         t.p(style="text-align: center")["===>",t.strong[next(inside_counter)+1],"<==="]
     ]
Esempio n. 56
0
 def render_availability(self, ctx, data):
     if self.product.availabilityDescription is not None:
         return T.p(class_='availability')[T.strong['availability: '],self.product.availabilityDescription]
     else:
         return ''
Esempio n. 57
0
def formatFailure(myFailure):
    if not isinstance(myFailure, failure.Failure):
        return t.pre[ str(myFailure) ]

    stackTrace = t.div(_class="stackTrace")
    failureOverview = t.p(_class="error")[ str(myFailure.type), ": ", str(myFailure.value) ]

    result = [
        t.style(type="text/css")[
            stylesheet,
        ],
        t.a(href="#tracebackEnd")[ failureOverview ],
        stackTrace,
        t.a(name="tracebackEnd")[ failureOverview ]
    ]

    first = 1
    for method, filename, lineno, localVars, globalVars in myFailure.frames:
        # It's better to have a line number than nothing at all.
        #if filename == '<string>':
        #    continue
        if first:
            frame = t.div(_class="firstFrame")
            first = 0
        else:
            frame = t.div(_class="frame")
        stackTrace[ frame ]

        snippet = t.div(_class="snippet")
        frame[
            t.div(_class="location")[
                filename, ", line ", lineno, " in ", t.span(_class="function")[ method ]
            ],
            snippet,
        ]

        textSnippet = ''
        for snipLineNo in range(lineno-2, lineno+2):
            snipLine = linecache.getline(filename, snipLineNo)
            textSnippet += snipLine
            if snipLineNo == lineno:
                snippetClass = "snippetHighlightLine"
            else:
                snippetClass = "snippetLine"
            snippet[
                t.div(_class=snippetClass)[
                    t.span(_class="lineno")[ snipLineNo ],
                    t.pre(_class="code")[ snipLine ]
                ]
            ]

        # Instance variables
        for name, var in localVars:
            if name == 'self' and hasattr(var, '__dict__'):
                usedVars = [ (key, value) for (key, value) in var.__dict__.items()
                             if re.search(r'\Wself.%s\W' % (re.escape(key),), textSnippet) ]
                if usedVars:
                    frame[
                        t.div(_class="variables")[
                            t.strong(_class="variableClass")[ "Self" ],
                            varTable(usedVars)
                        ]
                    ]
                    break

        # Local and global vars
        for nm, varList in ('Locals', localVars), ('Globals', globalVars):
            usedVars = [ (name, var) for (name, var) in varList
                         if re.search(r'\W%s\W' % (re.escape(name),), textSnippet) ]
            if usedVars:
                frame[
                    t.div(_class="variables")[ t.strong(_class="variableClass")[ nm ] ],
                    varTable(usedVars)
                ]

    return result