paulb@1 | 1 | #!/usr/bin/env python |
paulb@1 | 2 | |
paulb@1 | 3 | """ |
paulb@1 | 4 | XSL-based form templating. |
paulb@1 | 5 | """ |
paulb@1 | 6 | |
paulb@1 | 7 | import libxslt |
paulb@1 | 8 | |
paulb@1 | 9 | """ |
paulb@1 | 10 | import libxml2 |
paulb@1 | 11 | |
paulb@1 | 12 | def quiet(context, s): |
paulb@1 | 13 | pass |
paulb@1 | 14 | |
paulb@1 | 15 | libxml2.registerErrorHandler(quiet, None) |
paulb@1 | 16 | """ |
paulb@1 | 17 | |
paulb@9 | 18 | def path_to_node(node, name): |
paulb@1 | 19 | |
paulb@9 | 20 | """ |
paulb@9 | 21 | Generate an XSLForms path to the given 'node', using the given 'name' to |
paulb@9 | 22 | complete the path if an attribute reference is required (otherwise 'name' |
paulb@9 | 23 | will be None). |
paulb@9 | 24 | """ |
paulb@1 | 25 | |
paulb@1 | 26 | l = [] |
paulb@6 | 27 | # Skip attribute reference. |
paulb@6 | 28 | if node.type == "attribute": |
paulb@6 | 29 | node = node.parent |
paulb@9 | 30 | # Manually insert the attribute name if defined. |
paulb@9 | 31 | if name is not None: |
paulb@9 | 32 | l.insert(0, name) |
paulb@9 | 33 | l.insert(0, "/") |
paulb@1 | 34 | # Element references. |
paulb@1 | 35 | while node is not None and node.type != "document_xml": |
paulb@1 | 36 | l.insert(0, str(int(node.xpathEval("count(preceding-sibling::*) + 1")))) |
paulb@1 | 37 | l.insert(0, "#") |
paulb@1 | 38 | l.insert(0, node.name) |
paulb@1 | 39 | l.insert(0, "/") |
paulb@1 | 40 | node = node.parent |
paulb@1 | 41 | return "".join(l) |
paulb@1 | 42 | |
paulb@1 | 43 | def this_position(context): |
paulb@1 | 44 | |
paulb@1 | 45 | """ |
paulb@1 | 46 | As a libxslt extension function, return a string containing the XSLForms |
paulb@9 | 47 | path to the 'context' node, using the special "this-name" variable to |
paulb@9 | 48 | complete the path if an attribute reference is required. |
paulb@1 | 49 | """ |
paulb@1 | 50 | |
paulb@1 | 51 | pctxt = libxslt.xpathParserContext(_obj=context) |
paulb@1 | 52 | context = pctxt.context() |
paulb@1 | 53 | node = context.contextNode() |
paulb@9 | 54 | transform_context = context.transformContext() |
paulb@9 | 55 | name_var = transform_context.variableLookup("this-name", None) |
paulb@9 | 56 | if name_var is not None: |
paulb@9 | 57 | name = name_var[0].content |
paulb@9 | 58 | else: |
paulb@9 | 59 | name = None |
paulb@9 | 60 | return path_to_node(node, name) |
paulb@1 | 61 | |
paulb@1 | 62 | libxslt.registerExtModuleFunction("this-position", "http://www.boddie.org.uk/ns/xmltools/template", this_position) |
paulb@1 | 63 | |
paulb@1 | 64 | # vim: tabstop=4 expandtab shiftwidth=4 |