Пример #1
0
def URLSerializer(original, context):
    urlContext = WovenContext(parent=context,
                              precompile=context.precompile,
                              inURL=True)
    if original.scheme:
        yield "%s://%s" % (original.scheme, original.netloc)
    for pathsegment in original._qpathlist:
        yield '/'
        yield serialize(pathsegment, urlContext)
    query = original._querylist
    if query:
        yield '?'
        first = True
        for key, value in query:
            if not first:
                yield '&'
            else:
                first = False
            yield serialize(key, urlContext)
            if value is not None:
                yield '='
                yield serialize(value, urlContext)
    if original.fragment:
        yield "#"
        yield serialize(original.fragment, urlContext)
Пример #2
0
def URLSerializer(original, context):
    """
    Serialize the given L{URL}.

    Unicode path, query and fragment components are handled according to the
    IRI standard (RFC 3987).
    """
    urlContext = WovenContext(parent=context, precompile=context.precompile, inURL=True)
    if original.scheme:
        # TODO: handle Unicode (see #2409)
        yield "%s://%s" % (original.scheme, original.netloc)
    for pathsegment in original._qpathlist:
        yield '/'
        yield serialize(pathsegment, urlContext)
    query = original._querylist
    if query:
        yield '?'
        first = True
        for key, value in query:
            if not first:
                # xhtml can't handle unescaped '&'
                if context.isAttrib is True:
                    yield '&'
                else:
                    yield '&'
            else:
                first = False
            yield serialize(key, urlContext)
            if value is not None:
                yield '='
                yield serialize(value, urlContext)
    if original.fragment:
        yield "#"
        yield serialize(original.fragment, urlContext)
Пример #3
0
def URLSerializer(original, context):
    urlContext = WovenContext(parent=context, precompile=context.precompile, inURL=True)
    if original.scheme:
        yield "%s://%s" % (original.scheme, original.netloc)
    for pathsegment in original._qpathlist:
        yield '/'
        yield serialize(pathsegment, urlContext)
    query = original._querylist
    if query:
        yield '?'
        first = True
        for key, value in query:
            if not first:
                # xhtml can't handle unescaped '&'
                if context.isAttrib is True:
                    yield '&'
                else:
                    yield '&'
            else:
                first = False
            yield serialize(key, urlContext)
            if value is not None:
                yield '='
                yield serialize(value, urlContext)
    if original.fragment:
        yield "#"
        yield serialize(original.fragment, urlContext)
Пример #4
0
def SlotSerializer(original, context):
    """
    Serialize a slot.

    If the value is already available in the given context, serialize and
    return it.  Otherwise, if this is a precompilation pass, return a new
    kind of slot which captures the current render context, so that any
    necessary quoting may be performed.  Otherwise, raise an exception
    indicating that the slot cannot be serialized.
    """
    if context.precompile:
        try:
            data = context.locateSlotData(original.name)
        except KeyError:
            return _PrecompiledSlot(
                original.name,
                precompile(original.children, context),
                original.default,
                context.isAttrib,
                context.inURL,
                context.inJS,
                context.inJSSingleQuoteString,
                original.filename,
                original.lineNumber,
                original.columnNumber,
            )
        else:
            return serialize(data, context)
    try:
        data = context.locateSlotData(original.name)
    except KeyError:
        if original.default is None:
            raise
        data = original.default
    return serialize(data, context)
Пример #5
0
    def test_reloadAfterPrecompile(self):
        """
        """
        # Get a filename
        temp = self.mktemp()

        # Write some content
        f = file(temp, 'w')
        f.write('<p>foo</p>')
        f.close()

        # Precompile the doc
        ctx = context.WovenContext()
        doc = loaders.htmlfile(temp)
        pc = flat.precompile(flat.flatten(doc), ctx)

        before = ''.join(flat.serialize(pc, ctx))


        # Write the file with different content and make sure the
        # timestamp changes
        f = file(temp, 'w')
        f.write('<p>bar</p>')
        f.close()
        os.utime(temp, (os.path.getatime(temp), os.path.getmtime(temp)+5))

        after = ''.join(flat.serialize(pc, ctx))

        self.assertIn('foo', before)
        self.assertIn('bar', after)
        self.failIfEqual(before, after)
Пример #6
0
def SlotSerializer(original, context):
    """
    Serialize a slot.

    If the value is already available in the given context, serialize and
    return it.  Otherwise, if this is a precompilation pass, return a new
    kind of slot which captures the current render context, so that any
    necessary quoting may be performed.  Otherwise, raise an exception
    indicating that the slot cannot be serialized.
    """
    if context.precompile:
        try:
            data = context.locateSlotData(original.name)
        except KeyError:
            return _PrecompiledSlot(original.name,
                                    precompile(original.children, context),
                                    original.default, context.isAttrib,
                                    context.inURL, context.inJS,
                                    context.inJSSingleQuoteString)
        else:
            return serialize(data, context)
    try:
        data = context.locateSlotData(original.name)
    except KeyError:
        if original.default is None:
            raise
        data = original.default
    return serialize(data, context)
Пример #7
0
def MicroDomElementSerializer(element, context):
    directiveMapping = {
        'render': 'render',
        'data': 'data',
        'macro': 'macro',
    }
    attributeList = [
        'pattern',
        'key',
    ]

    name = element.tagName
    if name.startswith('nevow:'):
        _, name = name.split(':')
        if name == 'invisible':
            name = ''
        elif name == 'slot':
            return slot(element.attributes['name'])[precompile(
                serialize(element.childNodes, context), context)]

    attrs = dict(element.attributes)  # get rid of CaseInsensitiveDict
    specials = {}
    attributes = attributeList
    directives = directiveMapping
    for k, v in list(attrs.items()):
        # I know, this is totally not the way to do xml namespaces but who cares right now
        ## I'll fix it later -dp
        ### no you won't *I'll* fix it later -glyph
        if isinstance(k, tuple):
            if k[0] != 'http://nevow.com/ns/nevow/0.1':
                continue
            else:
                nons = k[1]
        elif not k.startswith('nevow:'):
            continue
        else:
            _, nons = k.split(':')
        if nons in directives:
            ## clean this up by making the names more consistent
            specials[directives[nons]] = directive(v)
            del attrs[k]
        if nons in attributes:
            specials[nons] = v
            del attrs[k]

    # TODO: there must be a better way than this ...
    # Handle any nevow:attr elements. If we don't do it now then this tag will
    # be serialised and it will too late.
    childNodes = []
    for child in element.childNodes:
        if getattr(child, 'tagName', None) == 'nevow:attr':
            attrs[child.attributes['name']] = child.childNodes
        else:
            childNodes.append(child)

    tag = Tag(name, attributes=attrs, children=childNodes, specials=specials)

    return serialize(tag, context)
def inlineJSSerializer(original, ctx):
    from nevow import livepage
    from nevow.tags import script, xml
    theJS = livepage.js(original.children)
    new = livepage.JavascriptContext(ctx, invisible[theJS])
    return serialize(script(type="text/javascript")[
        xml('\n//<![CDATA[\n'),
        serialize(theJS, new),
        xml('\n//]]>\n')], ctx)
Пример #9
0
def inlineJSSerializer(original, ctx):
    from nevow import livepage
    from nevow.tags import script, xml
    theJS = livepage.js(original.children)
    new = livepage.JavascriptContext(ctx, invisible[theJS])
    return serialize(
        script(type="text/javascript")[xml('\n//<![CDATA[\n'),
                                       serialize(theJS, new),
                                       xml('\n//]]>\n')], ctx)
Пример #10
0
def MicroDomElementSerializer(element, context):
    directiveMapping = {
        'render': 'render',
        'data': 'data',
        'macro': 'macro',
    }
    attributeList = [
        'pattern', 'key',
    ]

    name = element.tagName
    if name.startswith('nevow:'):
        _, name = name.split(':')
        if name == 'invisible':
            name = ''
        elif name == 'slot':
            return slot(element.attributes['name'])[
                precompile(serialize(element.childNodes, context), context)]
    
    attrs = dict(element.attributes) # get rid of CaseInsensitiveDict
    specials = {}
    attributes = attributeList
    directives = directiveMapping
    for k, v in attrs.items():
        # I know, this is totally not the way to do xml namespaces but who cares right now
        ## I'll fix it later
        if not k.startswith('nevow:'):
            continue
        _, nons = k.split(':')
        if nons in directives:
            ## clean this up by making the names more consistent
            specials[directives[nons]] = directive(v)
            del attrs[k]
        if nons in attributes:
            specials[nons] = v
            del attrs[k]
            
    # TODO: there must be a better way than this ...
    # Handle any nevow:attr elements. If we don't do it now then this tag will
    # be serialised and it will too late.
    childNodes = []
    for child in element.childNodes:
        if getattr(child,'tagName',None) == 'nevow:attr':
            attrs[child.attributes['name']] = child.childNodes
        else:
            childNodes.append(child)

    tag = Tag(
            name,
            attributes=attrs,
            children=childNodes,
            specials=specials
            )

    return serialize(tag, context)
Пример #11
0
def SlotSerializer(original, context):
    if context.precompile:
        try:
            return serialize(context.locateSlotData(original.name), context)
        except KeyError:
            original.children = precompile(original.children, context)
        return original
    try:
        data = context.locateSlotData(original.name)
    except KeyError:
        if original.default is None:
            raise
        return serialize(original.default, context)
    return serialize(data, context)
Пример #12
0
def MicroDomElementSerializer(element, context):
    directiveMapping = {"render": "render", "data": "data", "macro": "macro"}
    attributeList = ["pattern", "key"]

    name = element.tagName
    if name.startswith("nevow:"):
        _, name = name.split(":")
        if name == "invisible":
            name = ""
        elif name == "slot":
            return slot(element.attributes["name"])[precompile(serialize(element.childNodes, context), context)]

    attrs = dict(element.attributes)  # get rid of CaseInsensitiveDict
    specials = {}
    attributes = attributeList
    directives = directiveMapping
    for k, v in attrs.items():
        # I know, this is totally not the way to do xml namespaces but who cares right now
        ## I'll fix it later -dp
        ### no you won't *I'll* fix it later -glyph
        if isinstance(k, tuple):
            if k[0] != "http://nevow.com/ns/nevow/0.1":
                continue
            else:
                nons = k[1]
        elif not k.startswith("nevow:"):
            continue
        else:
            _, nons = k.split(":")
        if nons in directives:
            ## clean this up by making the names more consistent
            specials[directives[nons]] = directive(v)
            del attrs[k]
        if nons in attributes:
            specials[nons] = v
            del attrs[k]

    # TODO: there must be a better way than this ...
    # Handle any nevow:attr elements. If we don't do it now then this tag will
    # be serialised and it will too late.
    childNodes = []
    for child in element.childNodes:
        if getattr(child, "tagName", None) == "nevow:attr":
            attrs[child.attributes["name"]] = child.childNodes
        else:
            childNodes.append(child)

    tag = Tag(name, attributes=attrs, children=childNodes, specials=specials)

    return serialize(tag, context)
Пример #13
0
def SlotSerializer(original, context):
    if context.precompile:
        try:
            return serialize(context.locateSlotData(original.name), context)
        except KeyError:
            original.children = precompile(original.children, context)
        return original
    try:
        data = context.locateSlotData(original.name)
    except KeyError:
        if original.default is None:
            raise
        return serialize(original.default, context)
    return serialize(data, context)
Пример #14
0
def DirectiveSerializer(original, context):
    if context.precompile:
        return original

    rendererFactory = context.locate(IRendererFactory)
    renderer = rendererFactory.renderer(context, original.name)
    return serialize(renderer, context)
Пример #15
0
def PrecompiledSlotSerializer(original, context):
    """
    Serialize a pre-compiled slot.

    Return the serialized value of the slot or raise a KeyError if it has no
    value.
    """
    # Precompilation should _not_ be happening at this point, but Nevow is very
    # sloppy about precompiling multiple times, so sometimes we are in a
    # precompilation context.  In this case, there is nothing to do, just
    # return the original object.  The case which seems to exercise this most
    # often is the use of a pattern as the stan document given to the stan
    # loader.  The pattern has already been precompiled, but the stan loader
    # precompiles it again.  This case should be eliminated by adding a loader
    # for precompiled documents.
    if context.precompile:
        warnings.warn("[v0.9.9] Support for multiple precompilation passes is deprecated.", PendingDeprecationWarning)
        return original

    try:
        data = context.locateSlotData(original.name)
    except KeyError:
        if original.default is None:
            raise
        data = original.default
    originalContext = context.clone(deep=False)
    originalContext.isAttrib = original.isAttrib
    originalContext.inURL = original.inURL
    originalContext.inJS = original.inJS
    originalContext.inJSSingleQuoteString = original.inJSSingleQuoteString
    return serialize(data, originalContext)
Пример #16
0
def DirectiveSerializer(original, context):
    if context.precompile:
        return original

    rendererFactory = context.locate(IRendererFactory)
    renderer = rendererFactory.renderer(context, original.name)
    return serialize(renderer, context)
Пример #17
0
def PrecompiledSlotSerializer(original, context):
    """
    Serialize a pre-compiled slot.

    Return the serialized value of the slot or raise a KeyError if it has no
    value.
    """
    # Precompilation should _not_ be happening at this point, but Nevow is very
    # sloppy about precompiling multiple times, so sometimes we are in a
    # precompilation context.  In this case, there is nothing to do, just
    # return the original object.  The case which seems to exercise this most
    # often is the use of a pattern as the stan document given to the stan
    # loader.  The pattern has already been precompiled, but the stan loader
    # precompiles it again.  This case should be eliminated by adding a loader
    # for precompiled documents.
    if context.precompile:
        warnings.warn(
            "[v0.9.9] Support for multiple precompilation passes is deprecated.",
            PendingDeprecationWarning)
        return original

    try:
        data = context.locateSlotData(original.name)
    except KeyError:
        if original.default is None:
            raise
        data = original.default
    originalContext = context.clone(deep=False)
    originalContext.isAttrib = original.isAttrib
    originalContext.inURL = original.inURL
    originalContext.inJS = original.inJS
    originalContext.inJSSingleQuoteString = original.inJSSingleQuoteString
    return serialize(data, originalContext)
Пример #18
0
def MicroDomElementSerializer(element, context):
    directiveMapping = {
        'render': 'render',
        'data': 'data',
        'macro': 'macro',
    }
    attributeList = [
        'pattern', 'key',
    ]
    name = element.tagName
    if name.startswith('nevow:'):
        _, name = name.split(':')
        if name == 'invisible':
            name = ''
        elif name == 'slot':
            return slot(element.attributes['name'])[
                precompile(serialize(element.childNodes, context), context)]
    attrs = dict(element.attributes) # get rid of CaseInsensitiveDict
    specials = {}
    attributes = attributeList
    directives = directiveMapping
    for k, v in attrs.items():
        if not k.startswith('nevow:'):
            continue
        _, nons = k.split(':')
        if nons in directives:
            specials[directives[nons]] = directive(v)
            del attrs[k]
        if nons in attributes:
            specials[nons] = v
            del attrs[k]
    childNodes = []
    for child in element.childNodes:
        if getattr(child,'tagName',None) == 'nevow:attr':
            attrs[child.attributes['name']] = child.childNodes
        else:
            childNodes.append(child)
    tag = Tag(
            name,
            attributes=attrs,
            children=childNodes,
            specials=specials
            )
    return serialize(tag, context)
Пример #19
0
 def test_reloadAfterPrecompile(self):
     """
     """
     temp = self.mktemp()
     f = file(temp, 'w')
     f.write('<p>foo</p>')
     f.close()
     ctx = context.WovenContext()
     doc = loaders.htmlfile(temp)
     pc = flat.precompile(flat.flatten(doc), ctx)
     before = ''.join(flat.serialize(pc, ctx))
     f = file(temp, 'w')
     f.write('<p>bar</p>')
     f.close()
     os.utime(temp, (os.path.getatime(temp), os.path.getmtime(temp)+5))
     after = ''.join(flat.serialize(pc, ctx))
     self.assertIn('foo', before)
     self.assertIn('bar', after)
     self.failIfEqual(before, after)
Пример #20
0
 def renderInlineException(self, context, reason):
     from nevow import failure
     formatted = failure.formatFailure(reason)
     desc = str(reason)
     return flat.serialize([
         stan.xml(
             """<div style="border: 1px dashed red; color: red; clear: both" onclick="this.childNodes[1].style.display = this.childNodes[1].style.display == 'none' ? 'block': 'none'">"""
         ), desc,
         stan.xml('<div style="display: none">'), formatted,
         stan.xml('</div></div>')
     ], context)
Пример #21
0
 def renderInlineException(self, context, reason):
     from nevow import failure
     formatted = failure.formatFailure(reason)
     desc = str(reason)
     return flat.serialize([
         stan.xml("""<div style="border: 1px dashed red; color: red; clear: both" onclick="this.childNodes[1].style.display = this.childNodes[1].style.display == 'none' ? 'block': 'none'">"""),
         desc,
         stan.xml('<div style="display: none">'),
         formatted,
         stan.xml('</div></div>')
     ], context)
Пример #22
0
def FunctionSerializer(original, context, nocontextfun=FunctionSerializer_nocontext):
    if context.precompile:
        return WovenContext(tag=invisible(render=original))
    else:
        data = convertToData(context.locate(IData), context)
        try:
            nocontext = nocontextfun(original)
            if nocontext is True:
                result = original(data)
            else:
                if nocontext is PASS_SELF:
                    renderer = context.locate(IRenderer)
                    result = original(renderer, context, data)
                else:
                    result = original(context, data)
        except StopIteration:
            raise RuntimeError, "User function %r raised StopIteration." % original
        serialized = serialize(result, context)
        if isinstance(serialized, (util.Deferred)):
            return serialized.addCallback(lambda r: serialize(r, context))
        return serialized
Пример #23
0
def URLOverlaySerializer(original, context):
    if context.precompile:
        yield original
    else:
        url = original.urlaccessor(context)
        for (cmd, args, kw) in original.dolater:
            url = getattr(url, cmd)(*args, **kw)
        req = context.locate(inevow.IRequest)
        for key in original._keep:
            for value in req.args.get(key, []):
                url = url.add(key, value)
        yield serialize(url, context)
Пример #24
0
def URLOverlaySerializer(original, context):
    if context.precompile:
        yield original
    else:
        url = original.urlaccessor(context)
        for (cmd, args, kw) in original.dolater:
            url = getattr(url, cmd)(*args, **kw)
        req = context.locate(inevow.IRequest)
        for key in original._keep:
            for value in req.args.get(key, []):
                url = url.add(key, value)
        yield serialize(url, context)
Пример #25
0
def URLSerializer(original, context):
    """
    Serialize the given L{URL}.

    Unicode path, query and fragment components are handled according to the
    IRI standard (RFC 3987).
    """
    def _maybeEncode(s):
        if isinstance(s, str):
            s = s.encode('utf-8')
        return s
    urlContext = WovenContext(parent=context, precompile=context.precompile, inURL=True)
    if original.scheme:
        # TODO: handle Unicode (see #2409)
        yield b"%s://%s" % (toBytes(original.scheme), toBytes(original.netloc))
    for pathsegment in original._qpathlist:
        yield b'/'
        yield serialize(_maybeEncode(pathsegment), urlContext)
    query = original._querylist
    if query:
        yield b'?'
        first = True
        for key, value in query:
            if not first:
                # xhtml can't handle unescaped '&'
                if context.isAttrib is True:
                    yield b'&amp;'
                else:
                    yield b'&'
            else:
                first = False
            yield serialize(_maybeEncode(key), urlContext)
            if value is not None:
                yield b'='
                yield serialize(_maybeEncode(value), urlContext)
    if original.fragment:
        yield b"#"
        yield serialize(_maybeEncode(original.fragment), urlContext)
Пример #26
0
def URLSerializer(original, context):
    urlContext = WovenContext(parent=context, precompile=context.precompile, inURL=True)
    if original.scheme:
        yield "%s://%s" % (original.scheme, original.netloc)
    for pathsegment in original._qpathlist:
        yield "/"
        yield serialize(pathsegment, urlContext)
    query = original._querylist
    if query:
        yield "?"
        first = True
        for key, value in query:
            if not first:
                yield "&"
            else:
                first = False
            yield serialize(key, urlContext)
            if value is not None:
                yield "="
                yield serialize(value, urlContext)
    if original.fragment:
        yield "#"
        yield serialize(original.fragment, urlContext)
Пример #27
0
def FunctionSerializer(original,
                       context,
                       nocontextfun=FunctionSerializer_nocontext):
    if context.precompile:
        return WovenContext(tag=invisible(render=original))
    else:
        data = convertToData(context.locate(IData), context)
        try:
            nocontext = nocontextfun(original)
            if nocontext is True:
                result = original(data)
            else:
                if nocontext is PASS_SELF:
                    renderer = context.locate(IRenderer)
                    result = original(renderer, context, data)
                else:
                    result = original(context, data)
        except StopIteration:
            raise RuntimeError, "User function %r raised StopIteration." % original
        serialized = serialize(result, context)
        if isinstance(serialized, (util.Deferred)):
            return serialized.addCallback(lambda r: serialize(r, context))
        return serialized
Пример #28
0
def entrySerializer(original, context):
    ul = tags.ul()
    for a,l in original.items():
        if len(l)==0:
            ul[tags.li[a, ': none']]
        elif len(l)==1:
            for attr in l:
                first = attr
                break
            ul[tags.li[a, ': ', first]]
        else:
            li=tags.li[a, ':']
            ul[li]
            liul=tags.ul()
            li[liul]
            for i in l:
                liul[tags.li[i]]
    return flat.serialize(ul, context)
Пример #29
0
def entrySerializer(original, context):
    ul = tags.ul()
    for a, l in original.items():
        if len(l) == 0:
            ul[tags.li[a, ': none']]
        elif len(l) == 1:
            for attr in l:
                first = attr
                break
            ul[tags.li[a, ': ', first]]
        else:
            li = tags.li[a, ':']
            ul[li]
            liul = tags.ul()
            li[liul]
            for i in l:
                liul[tags.li[i]]
    return flat.serialize(ul, context)
Пример #30
0
def FunctionSerializer(original, context, nocontextfun=FunctionSerializer_nocontext):
    if context.precompile:
        return WovenContext(tag=invisible(render=original))
    else:
        data = convertToData(context.locate(IData), context)
        try:
            nocontext = nocontextfun(original)
            if nocontext is True:
                result = original(data)
            else:
                if nocontext is PASS_SELF:
                    renderer = context.locate(IRenderer)
                    result = original(renderer, context, data)
                else:
                    result = original(context, data)
        except StopIteration:
            raise RuntimeError("User function %r raised StopIteration." % original)
        return serialize(result, context)
Пример #31
0
def flattenAttemptDeferred(d, ctx):
    def attemptComplete(ctx, result, reason=None):
        if result == 'success':
            d.callback(None)
        else:
            d.errback(ClientSideException(reason))

    transient = IClientHandle(ctx).transient(attemptComplete)
    return flat.serialize([
        _js("""try {
    """), d.stuff,
        _js("""
    """),
        transient('success'),
        _js("""
} catch (e) {
    """),
        transient('failure', js.e),
        _js("}")
    ], ctx)
Пример #32
0
def flattenAttemptDeferred(d, ctx):
    def attemptComplete(ctx, result, reason=None):
        if result == 'success':
            d.callback(None)
        else:
            d.errback(ClientSideException(reason))
    transient = IClientHandle(ctx).transient(attemptComplete)
    return flat.serialize([
_js("""try {
    """),
    d.stuff,
_js("""
    """),
    transient('success'),
_js("""
} catch (e) {
    """),
    transient('failure', js.e),
_js("}")
        ], ctx)
Пример #33
0
def FunctionSerializer(original, context, nocontextfun=FunctionSerializer_nocontext):
    if context.precompile:
        return WovenContext(tag=invisible(render=original))
    else:
        data = convertToData(context.locate(IData), context)
        try:
            nocontext = nocontextfun(original)
            if nocontext is True:
                if hasattr(original, "__code__") and (
                    original.__code__.co_argcount == 3
                    or (original.__code__.co_argcount == 2 and original.__code__.co_varnames[0] != "self")
                ):
                    result = original(context, data)
                else:
                    result = original(data)
            else:
                if nocontext is PASS_SELF:
                    renderer = context.locate(IRenderer)
                    result = original(renderer, context, data)
                else:
                    result = original(context, data)
        except StopIteration:
            raise RuntimeError("User function %r raised StopIteration." % original)
        return serialize(result, context)
Пример #34
0
def FailureSerializer(original, ctx):
    from nevow import failure
    return serialize(failure.formatFailure(original), ctx)
Пример #35
0
def flattenSingleQuote(singleQuote, ctx):
    new = JavascriptContext(ctx,
                            tags.invisible[singleQuote],
                            inJSSingleQuoteString=True)
    return flat.serialize(singleQuote.children, new)
Пример #36
0
def TagSerializer(original, context, contextIsMine=False):
    """
    Original is the tag.
    Context is either:
      - the context of someone up the chain (if contextIsMine is False)
      - this tag's context (if contextIsMine is True)
    """
    visible = bool(original.tagName)
    if visible and context.isAttrib:
        raise RuntimeError, "Tried to render tag '%s' in an tag attribute context." % (original.tagName)
    if context.precompile and original.macro:
        toBeRenderedBy = original.macro
        if isinstance(toBeRenderedBy, directive):
            toBeRenderedBy = IMacroFactory(context).macro(context, toBeRenderedBy.name)
        original.macro = Unset
        newContext = WovenContext(context, original)
        yield serialize(toBeRenderedBy(newContext), newContext)
        return
    if context.precompile and (
        [x for x in original._specials.values() 
        if x is not None and x is not Unset]
        or original.slotData):
        nestedcontext = WovenContext(precompile=context.precompile, isAttrib=context.isAttrib)
        original = original.clone(deep=False)
        if not contextIsMine:
            context = WovenContext(context, original)
        context.tag.children = precompile(context.tag.children, nestedcontext)
        yield context
        return
    if original.pattern is not Unset and original.pattern is not None:
        return
    if not contextIsMine:
        if original.render:
            original = original.clone(deep=False)
        context = WovenContext(context, original)
    if original.data is not Unset:
        newdata = convertToData(original.data, context)
        if isinstance(newdata, util.Deferred):
            yield newdata.addCallback(lambda newdata: _datacallback(newdata, context))
        else:
            _datacallback(newdata, context)
    if original.render:
        toBeRenderedBy = original.render
        original._clearSpecials()
        yield serialize(toBeRenderedBy, context)
        return
    if not visible:
        for child in original.children:
            yield serialize(child, context)
        return
    yield '<%s' % original.tagName
    if original.attributes:
        attribContext = WovenContext(parent=context, precompile=context.precompile, isAttrib=True)
        for (k, v) in original.attributes.iteritems():
            if v is None:
                continue
            yield ' %s="' % k
            yield serialize(v, attribContext)
            yield '"'
    if not original.children:
        if original.tagName in allowSingleton:
            yield ' />'
        else:
            yield '></%s>' % original.tagName
    else:
        yield '>'
        for child in original.children:
            yield serialize(child, context)        
        yield '</%s>' % original.tagName
Пример #37
0
def ListSerializer(original, context):
    for item in original:
        yield serialize(item, context)
Пример #38
0
def flattenTransient(transient, ctx):
    thing = js.server.handle("--transient.%s" % (transient.transientId, ),
                             *transient.arguments)
    return flat.serialize(thing, ctx)
Пример #39
0
def flattenSingleQuote(singleQuote, ctx):
    new = JavascriptContext(ctx, tags.invisible[singleQuote], inJSSingleQuoteString=True)
    return flat.serialize(singleQuote.children, new)
Пример #40
0
def CommentSerializer(original, context):
    yield "<!--"
    for x in original.children:
        yield serialize(x, context)
    yield "-->"
Пример #41
0
def FailureSerializer(original, ctx):
    from nevow import failure

    return serialize(failure.formatFailure(original), ctx)
Пример #42
0
def CommentSerializer(original, context):
    yield "<!--"
    for x in original.children:
        yield serialize(x, context)
    yield "-->"
Пример #43
0
def DocFactorySerializer(original, ctx):
    """Serializer for document factories.
    """
    return serialize(original.load(ctx), ctx)
Пример #44
0
def flattenJS(theJS, ctx):
    new = JavascriptContext(ctx, tags.invisible[theJS])
    return flat.serialize(theJS._children, new)
Пример #45
0
def TagSerializer(original, context, contextIsMine=False):
    """
    Original is the tag.
    Context is either:
      - the context of someone up the chain (if contextIsMine is False)
      - this tag's context (if contextIsMine is True)
    """
    #    print "TagSerializer:",original, "ContextIsMine",contextIsMine, "Context:",context
    visible = bool(original.tagName)

    if visible and context.isAttrib:
        raise RuntimeError, "Tried to render tag '%s' in an tag attribute context." % (
            original.tagName)

    if context.precompile and original.macro:
        toBeRenderedBy = original.macro
        ## Special case for directive; perhaps this could be handled some other way with an interface?
        if isinstance(toBeRenderedBy, directive):
            toBeRenderedBy = IMacroFactory(context).macro(
                context, toBeRenderedBy.name)
        original.macro = Unset
        newContext = WovenContext(context, original)
        yield serialize(toBeRenderedBy(newContext), newContext)
        return

    ## TODO: Do we really need to bypass precompiling for *all* specials?
    ## Perhaps just render?
    if context.precompile and ([
            x for x in original._specials.values()
            if x is not None and x is not Unset
    ] or original.slotData):
        ## The tags inside this one get a "fresh" parent chain, because
        ## when the context yielded here is serialized, the parent
        ## chain gets reconnected to the actual parents at that
        ## point, since the render function here could change
        ## the actual parentage hierarchy.
        nestedcontext = WovenContext(precompile=context.precompile,
                                     isAttrib=context.isAttrib)

        # If necessary, remember the MacroFactory onto the new context chain.
        macroFactory = IMacroFactory(context, None)
        if macroFactory is not None:
            nestedcontext.remember(macroFactory, IMacroFactory)

        original = original.clone(deep=False)
        if not contextIsMine:
            context = WovenContext(context, original)
        context.tag.children = precompile(context.tag.children, nestedcontext)

        yield context
        return

    ## Don't render patterns
    if original.pattern is not Unset and original.pattern is not None:
        return

    if not contextIsMine:
        if original.render:
            ### We must clone our tag before passing to a render function
            original = original.clone(deep=False)
        context = WovenContext(context, original)

    if original.data is not Unset:
        newdata = convertToData(original.data, context)
        if isinstance(newdata, util.Deferred):
            yield newdata.addCallback(
                lambda newdata: _datacallback(newdata, context))
        else:
            _datacallback(newdata, context)

    if original.render:
        ## If we have a render function we want to render what it returns,
        ## not our tag
        toBeRenderedBy = original.render
        # erase special attribs so if the renderer returns the tag,
        # the specials won't be on the context twice.
        original._clearSpecials()
        yield serialize(toBeRenderedBy, context)
        return

    if not visible:
        for child in original.children:
            yield serialize(child, context)
        return

    yield '<%s' % original.tagName
    if original.attributes:
        attribContext = WovenContext(parent=context,
                                     precompile=context.precompile,
                                     isAttrib=True)
        for (k, v) in original.attributes.iteritems():
            if v is None:
                continue
            yield ' %s="' % k
            yield serialize(v, attribContext)
            yield '"'
    if not original.children:
        if original.tagName in allowSingleton:
            yield ' />'
        else:
            yield '></%s>' % original.tagName
    else:
        yield '>'
        for child in original.children:
            yield serialize(child, context)
        yield '</%s>' % original.tagName
Пример #46
0
def flattenTransient(transient, ctx):
    thing = js.server.handle("--transient.%s" % (transient.transientId, ), *transient.arguments)
    return flat.serialize(thing, ctx)
Пример #47
0
def flattenJS(theJS, ctx):
    new = JavascriptContext(ctx, tags.invisible[theJS])
    return flat.serialize(theJS._children, new)
Пример #48
0
def ListSerializer(original, context):
    for item in original:
        yield serialize(item, context)
Пример #49
0
def DocFactorySerializer(original, ctx):
    """Serializer for document factories.
    """
    return serialize(original.load(ctx), ctx)
Пример #50
0
def dnSerializer(original, context):
    return flat.serialize(str(original), context)
Пример #51
0
def TagSerializer(original, context, contextIsMine=False):
    """
    Original is the tag.
    Context is either:
      - the context of someone up the chain (if contextIsMine is False)
      - this tag's context (if contextIsMine is True)
    """
    #    print "TagSerializer:",original, "ContextIsMine",contextIsMine, "Context:",context
    visible = bool(original.tagName)

    if visible and context.isAttrib:
        raise RuntimeError("Tried to render tag '%s' in an tag attribute context." % (original.tagName))

    if context.precompile and original.macro:
        toBeRenderedBy = original.macro
        ## Special case for directive; perhaps this could be handled some other way with an interface?
        if isinstance(toBeRenderedBy, directive):
            toBeRenderedBy = IMacroFactory(context).macro(context, toBeRenderedBy.name)
        original.macro = Unset
        newContext = WovenContext(context, original)
        yield serialize(toBeRenderedBy(newContext), newContext)
        return

    ## TODO: Do we really need to bypass precompiling for *all* specials?
    ## Perhaps just render?
    if context.precompile and (
        [x for x in list(original._specials.values()) if x is not None and x is not Unset] or original.slotData
    ):
        ## The tags inside this one get a "fresh" parent chain, because
        ## when the context yielded here is serialized, the parent
        ## chain gets reconnected to the actual parents at that
        ## point, since the render function here could change
        ## the actual parentage hierarchy.
        nestedcontext = WovenContext(precompile=context.precompile, isAttrib=context.isAttrib)

        # If necessary, remember the MacroFactory onto the new context chain.
        macroFactory = IMacroFactory(context, None)
        if macroFactory is not None:
            nestedcontext.remember(macroFactory, IMacroFactory)

        original = original.clone(deep=False)
        if not contextIsMine:
            context = WovenContext(context, original)
        context.tag.children = precompile(context.tag.children, nestedcontext)

        yield context
        return

    ## Don't render patterns
    if original.pattern is not Unset and original.pattern is not None:
        return

    if not contextIsMine:
        if original.render:
            ### We must clone our tag before passing to a render function
            original = original.clone(deep=False)
        context = WovenContext(context, original)

    if original.data is not Unset:
        newdata = convertToData(original.data, context)
        if isinstance(newdata, util.Deferred):
            yield newdata.addCallback(lambda newdata: _datacallback(newdata, context))
        else:
            _datacallback(newdata, context)

    if original.render:
        ## If we have a render function we want to render what it returns,
        ## not our tag
        toBeRenderedBy = original.render
        # erase special attribs so if the renderer returns the tag,
        # the specials won't be on the context twice.
        original._clearSpecials()
        yield serialize(toBeRenderedBy, context)
        return

    if not visible:
        for child in original.children:
            yield serialize(child, context)
        return

    yield "<%s" % original.tagName
    if original.attributes:
        attribContext = WovenContext(parent=context, precompile=context.precompile, isAttrib=True)
        for (k, v) in sorted(original.attributes.items()):
            if v is None:
                continue
            yield ' %s="' % k
            yield serialize(v, attribContext)
            yield '"'
    if not original.children:
        if original.tagName in allowSingleton:
            yield " />"
        else:
            yield "></%s>" % original.tagName
    else:
        yield ">"
        for child in original.children:
            yield serialize(child, context)
        yield "</%s>" % original.tagName
Пример #52
0
def MicroDomDocumentSerializer(original, context):
    if original.doctype:
        yield "<!DOCTYPE %s>\n" % original.doctype
    for n in original.childNodes:
        yield serialize(n, context)
Пример #53
0
def dnSerializer(original, context):
    return flat.serialize(str(original), context)
Пример #54
0
def MicroDomDocumentSerializer(original, context):
    if original.doctype:
        yield "<!DOCTYPE %s>\n" % original.doctype
    for n in original.childNodes:
        yield serialize(n, context)