Debian Codegraph @

simpletal/simpleTAL.py

raw symbols SCIP
1 """ simpleTAL Interpreter
2
3 Copyright (c) 2009 Colin Stewart (http://www.owlfish.com/)
4 All rights reserved.
5
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9 1. Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11 2. Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14 3. The name of the author may not be used to endorse or promote products
15 derived from this software without specific prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 If you make any bug fixes or feature enhancements please let me know!
29
30
31 The classes in this module implement the TAL language, expanding
32 both XML and HTML templates.
33
34 Module Dependencies: logging, simpleTALES, simpleTALTemplates
35 """
36
37 import logging
38
39 import xml.sax, xml.sax.saxutils,html, io, re, types, codecs
40 import simpletal, copy, sys
41 from . import FixedHTMLParser, sgmlentitynames
42
43 __version__ = simpletal.__version__
44
45 try:
46 # Is PyXML's LexicalHandler available?
47 from xml.sax.saxlib import LexicalHandler
48 use_lexical_handler = 1
49 except ImportError:
50 use_lexical_handler = 0
51 class LexicalHandler:
52 pass
53
54 try:
55 # Is PyXML's DOM2SAX available?
56 import xml.dom.ext.Dom2Sax
57 use_dom2sax = 1
58 except ImportError:
59 use_dom2sax = 0
60
61 # Check Python version. If 3.3 or later, all SGML entities will be expanded in the HTML Parser
62 if sys.version_info[0] > 3 or (sys.version_info[0] == 3 and sys.version_info[1] > 3):
63 HTML_ENTITIES_PRE_EXPANDED = True
64 else:
65 HTML_ENTITIES_PRE_EXPANDED = False
66
67 from . import simpleTALES
68
69 # Name-space URIs
70 METAL_NAME_URI="http://xml.zope.org/namespaces/metal"
71 TAL_NAME_URI="http://xml.zope.org/namespaces/tal"
72
73 # All commands are of the form (opcode, args, commandList)
74 # The numbers are the opcodes, and also the order of priority
75
76 # Argument: [(isLocalFlag (Y/n), variableName, variablePath),...]
77 TAL_DEFINE = 1
78 # Argument: expression, endTagSymbol
79 TAL_CONDITION = 2
80 # Argument: (varname, expression, endTagSymbol)
81 TAL_REPEAT = 3
82 # Argument: (replaceFlag, type, expression)
83 TAL_CONTENT = 4
84 # Not used in byte code, only ordering.
85 TAL_REPLACE = 5
86 # Argument: [(attributeName, expression)]
87 TAL_ATTRIBUTES = 6
88 # Argument: expression
89 TAL_OMITTAG = 7
90 # Argument: (originalAttributeList, currentAttributeList)
91 TAL_START_SCOPE = 8
92 # Argument: String to output
93 TAL_OUTPUT = 9
94 # Argument: None
95 TAL_STARTTAG = 10
96 # Argument: Tag, omitTagFlag
97 TAL_ENDTAG_ENDSCOPE = 11
98 # Argument: None
99 TAL_NOOP = 13
100
101 # METAL Starts here
102 # Argument: expression, slotParams, endTagSymbol
103 METAL_USE_MACRO = 14
104 # Argument: macroName, endTagSymbol
105 METAL_DEFINE_SLOT=15
106 # Only used for parsing
107 METAL_FILL_SLOT=16
108 METAL_DEFINE_MACRO=17
109
110 METAL_NAME_REGEX = re.compile ("[a-zA-Z_][a-zA-Z0-9_]*")
111 SINGLETON_XML_REGEX = re.compile ('^<[^\s/>]+(?:\s*[^=>]+="[^">]+")*\s*/>')
112 SINGLETON_BYTES_XML_REGEX = re.compile (b'^<[^\s/>]+(?:\s*[^=>]+="[^">]+")*\s*/>')
113 ENTITY_REF_REGEX = re.compile (r'(?:&[a-zA-Z][\-\.a-zA-Z0-9]*[^\-\.a-zA-Z0-9])|(?:&#[xX]?[a-eA-E0-9]*[^0-9a-eA-E])')
114
115 # The list of elements in HTML that can not have end tags - done as a dictionary for fast
116 # lookup.
117 HTML_FORBIDDEN_ENDTAG = {'AREA': 1, 'BASE': 1, 'BASEFONT': 1, 'BR': 1, 'COL': 1
118 ,'FRAME': 1, 'HR': 1, 'IMG': 1, 'INPUT': 1, 'ISINDEX': 1
119 ,'LINK': 1, 'META': 1, 'PARAM': 1}
120
121 # List of element:attribute pairs that can use minimized form in HTML
122 HTML_BOOLEAN_ATTS = {'AREA:NOHREF': 1, 'IMG:ISMAP': 1, 'OBJECT:DECLARE': 1
123 , 'INPUT:CHECKED': 1, 'INPUT:DISABLED': 1, 'INPUT:READONLY': 1, 'INPUT:ISMAP': 1
124 , 'SELECT:MULTIPLE': 1, 'SELECT:DISABLED': 1
125 , 'OPTGROUP:DISABLED': 1
126 , 'OPTION:SELECTED': 1, 'OPTION:DISABLED': 1
127 , 'TEXTAREA:DISABLED': 1, 'TEXTAREA:READONLY': 1
128 , 'BUTTON:DISABLED': 1, 'SCRIPT:DEFER': 1}
129
130 class TemplateInterpreter:
131 def __init__ (self):
132 self.programStack = []
133 self.commandList = None
134 self.symbolTable = None
135 self.slotParameters = {}
136 self.commandHandler = {}
137 self.commandHandler [TAL_DEFINE] = self.cmdDefine
138 self.commandHandler [TAL_CONDITION] = self.cmdCondition
139 self.commandHandler [TAL_REPEAT] = self.cmdRepeat
140 self.commandHandler [TAL_CONTENT] = self.cmdContent
141 self.commandHandler [TAL_ATTRIBUTES] = self.cmdAttributes
142 self.commandHandler [TAL_OMITTAG] = self.cmdOmitTag
143 self.commandHandler [TAL_START_SCOPE] = self.cmdStartScope
144 self.commandHandler [TAL_OUTPUT] = self.cmdOutput
145 self.commandHandler [TAL_STARTTAG] = self.cmdOutputStartTag
146 self.commandHandler [TAL_ENDTAG_ENDSCOPE] = self.cmdEndTagEndScope
147 self.commandHandler [METAL_USE_MACRO] = self.cmdUseMacro
148 self.commandHandler [METAL_DEFINE_SLOT] = self.cmdDefineSlot
149 self.commandHandler [TAL_NOOP] = self.cmdNoOp
150
151 def tagAsText (self, tagObj, singletonFlag=0):
152 """ This returns a tag as text.
153 """
154 tag,atts = tagObj
155 result = ["<"]
156 result.append (tag)
157 for attName, attValue in atts:
158 result.append (' ')
159 result.append (attName)
160 result.append ('="')
161 result.append (html.escape (attValue, quote=1))
162 result.append ('"')
163 if (singletonFlag):
164 result.append (" />")
165 else:
166 result.append (">")
167 return "".join (result)
168
169 def initialise (self, context, outputFile):
170 self.context = context
171 self.file = outputFile
172
173 def cleanState (self):
174 self.scopeStack = []
175 self.programCounter = 0
176 self.movePCForward = None
177 self.movePCBack = None
178 self.outputTag = 1
179 self.originalAttributes = {}
180 self.currentAttributes = []
181 # Used in repeat only.
182 self.repeatAttributesCopy = []
183 self.currentSlots = {}
184 self.repeatVariable = None
185 self.tagContent = None
186 # tagState flag as to whether there are any local variables to pop
187 self.localVarsDefined = 0
188 # Pass in the parameters
189 self.currentSlots = self.slotParameters
190
191 def popProgram (self):
192 vars, self.commandList, self.symbolTable = self.programStack.pop()
193 self.programCounter,self.scopeStack,self.slotParameters,self.currentSlots, self.movePCForward,self.movePCBack,self.outputTag,self.originalAttributes,self.currentAttributes,self.repeatVariable,self.repeatAttributesCopy,self.tagContent,self.localVarsDefined = vars
194
195 def pushProgram (self):
196 vars = (self.programCounter
197 ,self.scopeStack
198 ,self.slotParameters
199 ,self.currentSlots
200 ,self.movePCForward
201 ,self.movePCBack
202 ,self.outputTag
203 ,self.originalAttributes
204 ,self.currentAttributes
205 ,self.repeatVariable
206 ,self.repeatAttributesCopy
207 ,self.tagContent
208 ,self.localVarsDefined)
209 self.programStack.append ((vars,self.commandList, self.symbolTable))
210
211 def execute (self, template):
212 self.cleanState()
213 self.commandList, self.programCounter, programLength, self.symbolTable = template.getProgram()
214 cmndList = self.commandList
215 while (self.programCounter < programLength):
216 cmnd = cmndList [self.programCounter]
217 #print "PC: %s - Executing command: %s" % (str (self.programCounter), str (cmnd))
218 self.commandHandler[cmnd[0]] (cmnd[0], cmnd[1])
219
220 def cmdDefine (self, command, args):
221 """ args: [(isLocalFlag (Y/n), variableName, variablePath),...]
222 Define variables in either the local or global context
223 """
224 foundLocals = 0
225 for isLocal, varName, varPath in args:
226 result = self.context.evaluate (varPath, self.originalAttributes)
227 if (isLocal):
228 if (not foundLocals):
229 foundLocals = 1
230 self.context.pushLocals ()
231 self.context.setLocal (varName, result)
232 else:
233 self.context.addGlobal (varName, result)
234 self.localVarsDefined = foundLocals
235 self.programCounter += 1
236
237 def cmdCondition (self, command, args):
238 """ args: expression, endTagSymbol
239 Conditionally continues with execution of all content contained
240 by it.
241 """
242 result = self.context.evaluate (args[0], self.originalAttributes)
243 #~ if (result is None or (not result)):
244 conditionFalse = 0
245 if (result is None):
246 conditionFalse = 1
247 else:
248 if (not result): conditionFalse = 1
249 try:
250 temp = len (result)
251 if (temp == 0): conditionFalse = 1
252 except:
253 # Result is not a sequence.
254 pass
255 if (conditionFalse):
256 # Nothing to output - evaluated to false.
257 self.outputTag = 0
258 self.tagContent = None
259 self.programCounter = self.symbolTable[args[1]]
260 return
261 self.programCounter += 1
262
263 def cmdRepeat (self, command, args):
264 """ args: (varName, expression, endTagSymbol)
265 Repeats anything in the cmndList
266 """
267 if (self.repeatVariable is not None):
268 # We are already part way through a repeat
269 # Restore any attributes that might have been changed.
270 if (self.currentAttributes != self.repeatAttributesCopy):
271 self.currentAttributes = copy.copy (self.repeatAttributesCopy)
272 self.outputTag = 1
273 self.tagContent = None
274 self.movePCForward = None
275
276 try:
277 self.repeatVariable.increment()
278 self.context.setLocal (args[0], self.repeatVariable.getCurrentValue())
279 self.programCounter += 1
280 return
281 except IndexError as e:
282 # We have finished the repeat
283 self.repeatVariable = None
284 self.context.removeRepeat (args[0])
285 # The locals were pushed in context.addRepeat
286 self.context.popLocals()
287 self.movePCBack = None
288 # Suppress the final close tag and content
289 self.tagContent = None
290 self.outputTag = 0
291 self.programCounter = self.symbolTable [args[2]]
292 # Restore the state of repeatAttributesCopy in case we are nested.
293 self.repeatAttributesCopy = self.scopeStack.pop()
294 return
295
296 # The first time through this command
297 result = self.context.evaluate (args[1], self.originalAttributes)
298 if (result is not None and result == simpleTALES.DEFAULTVALUE):
299 # Leave everything un-touched.
300 self.programCounter += 1
301 return
302 try:
303 # We have three options, either the result is a natural sequence, an iterator, or something that can produce an iterator.
304 isSequence = len (result)
305 if (isSequence):
306 # Only setup if we have a sequence with length
307 self.repeatVariable = simpleTALES.RepeatVariable (result)
308 else:
309 # Delete the tags and their contents
310 self.outputTag = 0
311 self.programCounter = self.symbolTable [args[2]]
312 return
313 except:
314 # Not a natural sequence, can it produce an iterator?
315 if (hasattr (result, "__iter__") and hasattr (result.__iter__, "__call__")):
316 # We can get an iterator!
317 self.repeatVariable = simpleTALES.IteratorRepeatVariable (result.__iter__())
318 elif (hasattr (result, "__next__") and hasattr (result.__next__, "__call__")):
319 # Treat as an iterator
320 self.repeatVariable = simpleTALES.IteratorRepeatVariable (result)
321 else:
322 # Just a plain object, let's not loop
323 # Delete the tags and their contents
324 self.outputTag = 0
325 self.programCounter = self.symbolTable [args[2]]
326 return
327
328 try:
329 curValue = self.repeatVariable.getCurrentValue()
330 except IndexError as e:
331 # The iterator ran out of values before we started - treat as an empty list
332 self.outputTag = 0
333 self.repeatVariable = None
334 self.programCounter = self.symbolTable [args[2]]
335 return
336 # We really do want to repeat - so lets do it
337 self.movePCBack = self.programCounter
338 self.context.addRepeat (args[0], self.repeatVariable, curValue)
339 # We keep the old state of the repeatAttributesCopy for nested loops
340 self.scopeStack.append (self.repeatAttributesCopy)
341 # Keep a copy of the current attributes for this tag
342 self.repeatAttributesCopy = copy.copy (self.currentAttributes)
343 self.programCounter += 1
344
345 def cmdContent (self, command, args):
346 """ args: (replaceFlag, structureFlag, expression, endTagSymbol)
347 Expands content
348 """
349 result = self.context.evaluate (args[2], self.originalAttributes)
350 if (result is None):
351 if (args[0]):
352 # Only output tags if this is a content not a replace
353 self.outputTag = 0
354 # Output none of our content or the existing content, but potentially the tags
355 self.movePCForward = self.symbolTable [args[3]]
356 self.programCounter += 1
357 return
358 elif (not result == simpleTALES.DEFAULTVALUE):
359 # We have content, so let's suppress the natural content and output this!
360 if (args[0]):
361 self.outputTag = 0
362 self.tagContent = (args[1], result)
363 self.movePCForward = self.symbolTable [args[3]]
364 self.programCounter += 1
365 return
366 else:
367 # Default, let's just run through as normal
368 self.programCounter += 1
369 return
370
371 def cmdAttributes (self, command, args):
372 """ args: [(attributeName, expression)]
373 Add, leave, or remove attributes from the start tag
374 """
375 attsToRemove = {}
376 newAtts = []
377 for attName, attExpr in args:
378 resultVal = self.context.evaluate (attExpr, self.originalAttributes)
379 if (resultVal is None):
380 # Remove this attribute from the current attributes
381 attsToRemove [attName]=1
382 elif (not resultVal == simpleTALES.DEFAULTVALUE):
383 # We have a value - let's use it!
384 attsToRemove [attName]=1
385 if (isinstance (resultVal, str)):
386 escapedAttVal = resultVal
387 elif (isinstance (resultVal, bytes)):
388 # THIS IS NOT A BUG!
389 # Use Unicode in the Context object if you are not using Ascii
390 escapedAttVal = str (resultVal, 'ascii')
391 else:
392 # THIS IS NOT A BUG!
393 # Use Unicode in the Context object if you are not using Ascii
394 escapedAttVal = str (resultVal)
395 newAtts.append ((attName, escapedAttVal))
396 # Copy over the old attributes
397 for oldAttName, oldAttValue in self.currentAttributes:
398 if (not oldAttName in attsToRemove):
399 newAtts.append ((oldAttName, oldAttValue))
400 self.currentAttributes = newAtts
401 # Evaluate all other commands
402 self.programCounter += 1
403
404 def cmdOmitTag (self, command, args):
405 """ args: expression
406 Conditionally turn off tag output
407 """
408 result = self.context.evaluate (args, self.originalAttributes)
409 if (result is not None and result):
410 # Turn tag output off
411 self.outputTag = 0
412 self.programCounter += 1
413
414 def cmdOutputStartTag (self, command, args):
415 # Args: tagName
416 tagName, singletonTag = args
417 if (self.outputTag):
418 if (self.tagContent is None and singletonTag):
419 self.file.write (self.tagAsText ((tagName, self.currentAttributes), 1))
420 else:
421 self.file.write (self.tagAsText ((tagName, self.currentAttributes)))
422
423 if (self.movePCForward is not None):
424 self.programCounter = self.movePCForward
425 return
426 self.programCounter += 1
427 return
428
429 def cmdEndTagEndScope (self, command, args):
430 # Args: tagName, omitFlag, singletonTag
431 if (self.tagContent is not None):
432 contentType, resultVal = self.tagContent
433 if (contentType):
434 if (isinstance (resultVal, Template)):
435 # We have another template in the context, evaluate it!
436 # Save our state!
437 self.pushProgram()
438 resultVal.expandInline (self.context, self.file, self)
439 # Restore state
440 self.popProgram()
441 # End of the macro expansion (if any) so clear the parameters
442 self.slotParameters = {}
443 else:
444 if (isinstance (resultVal, str)):
445 self.file.write (resultVal)
446 elif (isinstance (resultVal, bytes)):
447 # THIS IS NOT A BUG!
448 # Use Unicode in the Context object if you are not using Ascii
449 self.file.write (str (resultVal, 'ascii'))
450 else:
451 # THIS IS NOT A BUG!
452 # Use Unicode in the Context object if you are not using Ascii
453 self.file.write (str (resultVal))
454 else:
455 if (isinstance (resultVal, str)):
456 self.file.write (html.escape (resultVal, quote=False))
457 elif (isinstance (resultVal, bytes)):
458 # THIS IS NOT A BUG!
459 # Use Unicode in the Context object if you are not using Ascii
460 self.file.write (html.escape (str (resultVal, 'ascii'), quote=False))
461 else:
462 # THIS IS NOT A BUG!
463 # Use Unicode in the Context object if you are not using Ascii
464 self.file.write (html.escape (str (resultVal), quote=False))
465
466 if (self.outputTag and not args[1]):
467 # Do NOT output end tag if a singleton with no content
468 if not (args[2] and self.tagContent is None):
469 self.file.write ('</' + args[0] + '>')
470
471 if (self.movePCBack is not None):
472 self.programCounter = self.movePCBack
473 return
474
475 if (self.localVarsDefined):
476 self.context.popLocals()
477
478 self.movePCForward,self.movePCBack,self.outputTag,self.originalAttributes,self.currentAttributes,self.repeatVariable,self.tagContent,self.localVarsDefined = self.scopeStack.pop()
479 self.programCounter += 1
480
481 def cmdOutput (self, command, args):
482 self.file.write (args)
483 self.programCounter += 1
484
485 def cmdStartScope (self, command, args):
486 """ args: (originalAttributes, currentAttributes)
487 Pushes the current state onto the stack, and sets up the new state
488 """
489 self.scopeStack.append ((self.movePCForward
490 ,self.movePCBack
491 ,self.outputTag
492 ,self.originalAttributes
493 ,self.currentAttributes
494 ,self.repeatVariable
495 ,self.tagContent
496 ,self.localVarsDefined))
497
498 self.movePCForward = None
499 self.movePCBack = None
500 self.outputTag = 1
501 self.originalAttributes = args[0]
502 self.currentAttributes = args[1]
503 self.repeatVariable = None
504 self.tagContent = None
505 self.localVarsDefined = 0
506
507 self.programCounter += 1
508
509 def cmdNoOp (self, command, args):
510 self.programCounter += 1
511
512 def cmdUseMacro (self, command, args):
513 """ args: (macroExpression, slotParams, endTagSymbol)
514 Evaluates the expression, if it resolves to a SubTemplate it then places
515 the slotParams into currentSlots and then jumps to the end tag
516 """
517 value = self.context.evaluate (args[0], self.originalAttributes)
518 if (value is None):
519 # Don't output anything
520 self.outputTag = 0
521 # Output none of our content or the existing content
522 self.movePCForward = self.symbolTable [args[2]]
523 self.programCounter += 1
524 return
525 if (not value == simpleTALES.DEFAULTVALUE and isinstance (value, SubTemplate)):
526 # We have a macro, so let's use it
527 self.outputTag = 0
528 self.slotParameters = args[1]
529 self.tagContent = (1, value)
530 # NOTE: WE JUMP STRAIGHT TO THE END TAG, NO OTHER TAL/METAL COMMANDS ARE EVALUATED.
531 self.programCounter = self.symbolTable [args[2]]
532 return
533 else:
534 # Default, let's just run through as normal
535 self.programCounter += 1
536 return
537
538 def cmdDefineSlot (self, command, args):
539 """ args: (slotName, endTagSymbol)
540 If the slotName is filled then that is used, otherwise the original conent
541 is used.
542 """
543 if (args[0] in self.currentSlots):
544 # This slot is filled, so replace us with that content
545 self.outputTag = 0
546 self.tagContent = (1, self.currentSlots [args[0]])
547 # Output none of our content or the existing content
548 # NOTE: NO FURTHER TAL/METAL COMMANDS ARE EVALUATED
549 self.programCounter = self.symbolTable [args[1]]
550 return
551 # Slot isn't filled, so just use our own content
552 self.programCounter += 1
553 return
554
555
556 class HTMLTemplateInterpreter (TemplateInterpreter):
557 def __init__ (self, minimizeBooleanAtts = 0):
558 TemplateInterpreter.__init__ (self)
559 self.minimizeBooleanAtts = minimizeBooleanAtts
560 if (minimizeBooleanAtts):
561 # Override the tagAsText method for this instance
562 self.tagAsText = self.tagAsTextMinimizeAtts
563
564 def tagAsTextMinimizeAtts (self, tagObj, singletonFlag=0):
565 """ This returns a tag as text.
566 """
567 tag,atts = tagObj
568 result = ["<"]
569 result.append (tag)
570 upperTag = tag.upper()
571 for attName, attValue in atts:
572 if ('%s:%s' % (upperTag, attName.upper()) in HTML_BOOLEAN_ATTS):
573 # We should output a minimised boolean value
574 result.append (' ')
575 result.append (attName)
576 else:
577 result.append (' ')
578 result.append (attName)
579 result.append ('="')
580 result.append (html.escape (attValue, quote=1))
581 result.append ('"')
582 if (singletonFlag):
583 result.append (" />")
584 else:
585 result.append (">")
586 return "".join (result)
587
588 class Template:
589 def __init__ (self, commands, macros, symbols, doctype = None):
590 self.commandList = commands
591 self.macros = macros
592 self.symbolTable = symbols
593 self.doctype = doctype
594 self.log = logging.getLogger("simpleTAL.Template")
595
596 # Setup the macros
597 for macro in list(self.macros.values()):
598 macro.setParentTemplate (self)
599
600 # Setup the slots
601 for cmnd, arg in self.commandList:
602 if (cmnd == METAL_USE_MACRO):
603 # Set the parent of each slot
604 slotMap = arg[1]
605 for slot in list(slotMap.values()):
606 slot.setParentTemplate (self)
607
608 def expand (self, context, outputFile, outputEncoding=None, interpreter=None):
609 """ This method will write to the outputFile, using the encoding specified,
610 the expanded version of this template. The context passed in is used to resolve
611 all expressions with the template.
612 """
613 # This method must wrap outputFile if required by the encoding, and write out
614 # any template pre-amble (DTD, Encoding, etc)
615 self.expandInline (context, outputFile, interpreter)
616
617 def expandInline (self, context, outputFile, interpreter=None):
618 """ Internally used when expanding a template that is part of a context."""
619 if (interpreter is None):
620 ourInterpreter = TemplateInterpreter()
621 ourInterpreter.initialise (context, outputFile)
622 else:
623 ourInterpreter = interpreter
624 try:
625 ourInterpreter.execute (self)
626 except UnicodeError as unierror:
627 self.log.error ("UnicodeError caused by placing a non-Unicode string in the Context object.")
628 raise simpleTALES.ContextContentException ("Found non-unicode string in Context!")
629
630 def getProgram (self):
631 """ Returns a tuple of (commandList, startPoint, endPoint, symbolTable) """
632 return (self.commandList, 0, len (self.commandList), self.symbolTable)
633
634 def __str__ (self):
635 result = "Commands:\n"
636 index = 0
637 for cmd in self.commandList:
638 if (cmd[0] != METAL_USE_MACRO):
639 result = result + "\n[%s] %s" % (str (index), str (cmd))
640 else:
641 result = result + "\n[%s] %s, (%s{" % (str (index), str (cmd[0]), str (cmd[1][0]))
642 for slot in list(cmd[1][1].keys()):
643 result = result + "%s: %s" % (slot, str (cmd[1][1][slot]))
644 result = result + "}, %s)" % str (cmd[1][2])
645 index += 1
646 result = result + "\n\nSymbols:\n"
647 for symbol in list(self.symbolTable.keys()):
648 result = result + "Symbol: " + str (symbol) + " points to: " + str (self.symbolTable[symbol]) + ", which is command: " + str (self.commandList[self.symbolTable[symbol]]) + "\n"
649
650 result = result + "\n\nMacros:\n"
651 for macro in list(self.macros.keys()):
652 result = result + "Macro: " + str (macro) + " value of: " + str (self.macros[macro])
653 return result
654
655 class SubTemplate (Template):
656 """ A SubTemplate is part of another template, and is used for the METAL implementation.
657 The two uses for this class are:
658 1 - metal:define-macro results in a SubTemplate that is the macro
659 2 - metal:fill-slot results in a SubTemplate that is a parameter to metal:use-macro
660 """
661 def __init__ (self, startRange, endRangeSymbol):
662 """ The parentTemplate is the template for which we are a sub-template.
663 The startRange and endRange are indexes into the parent templates command list,
664 and defines the range of commands that we can execute
665 """
666 Template.__init__ (self, [], {}, {})
667 self.startRange = startRange
668 self.endRangeSymbol = endRangeSymbol
669
670 def setParentTemplate (self, parentTemplate):
671 self.parentTemplate = parentTemplate
672 self.commandList = parentTemplate.commandList
673 self.symbolTable = parentTemplate.symbolTable
674
675 def getProgram (self):
676 """ Returns a tuple of (commandList, startPoint, endPoint, symbolTable) """
677 return (self.commandList, self.startRange, self.symbolTable[self.endRangeSymbol]+1, self.symbolTable)
678
679 def __str__ (self):
680 endRange = self.symbolTable [self.endRangeSymbol]
681 result = "SubTemplate from %s to %s\n" % (str (self.startRange), str (endRange))
682 return result
683
684 class HTMLTemplate (Template):
685 """A specialised form of a template that knows how to output HTML
686 """
687 def __init__ (self, commands, macros, symbols, doctype = None, minimizeBooleanAtts = 0):
688 self.minimizeBooleanAtts = minimizeBooleanAtts
689 Template.__init__ (self, commands, macros, symbols, doctype = None)
690
691 def expand (self, context, outputFile, outputEncoding = "utf-8", interpreter=None):
692 """ This method will write to the outputFile the expanded version of this template.
693 The context passed in is used to resolve all expressions with the template.
694 """
695 if (isinstance (outputFile, io.TextIOBase) or isinstance (outputFile, codecs.StreamWriter)):
696 self.log.debug ("Text based output file detected")
697 else:
698 self.log.debug ("Bytes based output file detected - wrapping in codec for %s", outputEncoding)
699 outputFile = codecs.lookup (outputEncoding).streamwriter (outputFile, 'xmlcharrefreplace')
700 self.expandInline (context, outputFile, interpreter)
701
702 def expandInline (self, context, outputFile, interpreter=None):
703 """ Ensure we use the HTMLTemplateInterpreter"""
704 if (interpreter is None):
705 ourInterpreter = HTMLTemplateInterpreter(minimizeBooleanAtts = self.minimizeBooleanAtts)
706 ourInterpreter.initialise (context, outputFile)
707 else:
708 ourInterpreter = interpreter
709 Template.expandInline (self, context, outputFile, ourInterpreter)
710
711 class XMLTemplate (Template):
712 """A specialised form of a template that knows how to output XML
713 """
714
715 def __init__ (self, commands, macros, symbols, doctype = None):
716 Template.__init__ (self, commands, macros, symbols)
717 self.doctype = doctype
718
719 def expand (self, context, outputFile, outputEncoding = "utf-8", docType=None, suppressXMLDeclaration=False,interpreter=None):
720 """ This method will write to the outputFile, using the encoding attached to the outputFile,
721 the expanded version of this template. The context passed in is used to resolve
722 all expressions with the template.
723 """
724 if (isinstance (outputFile, io.TextIOBase) or isinstance (outputFile, codecs.StreamWriter)):
725 self.log.debug ("Text based output file detected")
726 else:
727 self.log.debug ("Bytes based output file detected - wrapping in codec for %s", outputEncoding)
728 outputFile = codecs.lookup (outputEncoding).streamwriter (outputFile, 'xmlcharrefreplace')
729
730 if (not suppressXMLDeclaration):
731 if (outputEncoding.lower() != "utf-8"):
732 outputFile.write ('<?xml version="1.0" encoding="%s"?>\n' % outputEncoding.lower())
733 else:
734 outputFile.write ('<?xml version="1.0"?>\n')
735 if not docType and self.doctype:
736 docType = self.doctype
737 if docType:
738 outputFile.write (docType)
739 outputFile.write ('\n')
740 self.expandInline (context, outputFile, interpreter)
741
742 class TemplateCompiler:
743 def __init__ (self):
744 """ Initialise a template compiler.
745 """
746 self.commandList = []
747 self.tagStack = []
748 self.symbolLocationTable = {}
749 self.macroMap = {}
750 self.endTagSymbol = 1
751
752 self.commandHandler = {}
753 self.commandHandler [TAL_DEFINE] = self.compileCmdDefine
754 self.commandHandler [TAL_CONDITION] = self.compileCmdCondition
755 self.commandHandler [TAL_REPEAT] = self.compileCmdRepeat
756 self.commandHandler [TAL_CONTENT] = self.compileCmdContent
757 self.commandHandler [TAL_REPLACE] = self.compileCmdReplace
758 self.commandHandler [TAL_ATTRIBUTES] = self.compileCmdAttributes
759 self.commandHandler [TAL_OMITTAG] = self.compileCmdOmitTag
760
761 # Metal commands
762 self.commandHandler [METAL_USE_MACRO] = self.compileMetalUseMacro
763 self.commandHandler [METAL_DEFINE_SLOT] = self.compileMetalDefineSlot
764 self.commandHandler [METAL_FILL_SLOT] = self.compileMetalFillSlot
765 self.commandHandler [METAL_DEFINE_MACRO] = self.compileMetalDefineMacro
766
767 # Default namespaces
768 self.setTALPrefix ('tal')
769 self.tal_namespace_prefix_stack = []
770 self.metal_namespace_prefix_stack = []
771 self.tal_namespace_prefix_stack.append ('tal')
772 self.setMETALPrefix ('metal')
773 self.metal_namespace_prefix_stack.append ('metal')
774
775 self.log = logging.getLogger ("simpleTAL.TemplateCompiler")
776
777 def setTALPrefix (self, prefix):
778 self.tal_namespace_prefix = prefix
779 self.tal_namespace_omittag = '%s:omit-tag' % self.tal_namespace_prefix
780 self.tal_attribute_map = {}
781 self.tal_attribute_map ['%s:attributes'%prefix] = TAL_ATTRIBUTES
782 self.tal_attribute_map ['%s:content'%prefix]= TAL_CONTENT
783 self.tal_attribute_map ['%s:define'%prefix] = TAL_DEFINE
784 self.tal_attribute_map ['%s:replace'%prefix] = TAL_REPLACE
785 self.tal_attribute_map ['%s:omit-tag'%prefix] = TAL_OMITTAG
786 self.tal_attribute_map ['%s:condition'%prefix] = TAL_CONDITION
787 self.tal_attribute_map ['%s:repeat'%prefix] = TAL_REPEAT
788
789 def setMETALPrefix (self, prefix):
790 self.metal_namespace_prefix = prefix
791 self.metal_attribute_map = {}
792 self.metal_attribute_map ['%s:define-macro'%prefix] = METAL_DEFINE_MACRO
793 self.metal_attribute_map ['%s:use-macro'%prefix] = METAL_USE_MACRO
794 self.metal_attribute_map ['%s:define-slot'%prefix] = METAL_DEFINE_SLOT
795 self.metal_attribute_map ['%s:fill-slot'%prefix] = METAL_FILL_SLOT
796
797 def popTALNamespace (self):
798 newPrefix = self.tal_namespace_prefix_stack.pop()
799 self.setTALPrefix (newPrefix)
800
801 def popMETALNamespace (self):
802 newPrefix = self.metal_namespace_prefix_stack.pop()
803 self.setMETALPrefix (newPrefix)
804
805 def tagAsText (self, tagObj, singletonFlag=0):
806 """ This returns a tag as text.
807 """
808 tag,atts = tagObj
809 result = ["<"]
810 result.append (tag)
811 for attName, attValue in atts:
812 result.append (' ')
813 result.append (attName)
814 result.append ('="')
815 result.append (html.escape (attValue, quote=1))
816 result.append ('"')
817 if (singletonFlag):
818 result.append (" />")
819 else:
820 result.append (">")
821 return "".join (result)
822
823 def getTemplate (self):
824 template = Template (self.commandList, self.macroMap, self.symbolLocationTable)
825 return template
826
827 def addCommand (self, command):
828 if (command[0] == TAL_OUTPUT and (len (self.commandList) > 0) and self.commandList[-1][0] == TAL_OUTPUT):
829 # We can combine output commands
830 self.commandList[-1] = (TAL_OUTPUT, self.commandList[-1][1] + command[1])
831 else:
832 self.commandList.append (command)
833
834 def addTag (self, tag, tagProperties={}):
835 """ Used to add a tag to the stack. Various properties can be passed in the dictionary
836 as being information required by the tag.
837 Currently supported properties are:
838 'command' - The (command,args) tuple associated with this command
839 'originalAtts' - The original attributes that include any metal/tal attributes
840 'endTagSymbol' - The symbol associated with the end tag for this element
841 'popFunctionList' - A list of functions to execute when this tag is popped
842 'singletonTag' - A boolean to indicate that this is a singleton flag
843 """
844 # Add the tag to the tagStack (list of tuples (tag, properties, useMacroLocation))
845 self.log.debug ("Adding tag %s to stack" % tag[0])
846 command = tagProperties.get ('command',None)
847 originalAtts = tagProperties.get ('originalAtts', None)
848 singletonTag = tagProperties.get ('singletonTag', 0)
849 if (command is not None):
850 if (command[0] == METAL_USE_MACRO):
851 self.tagStack.append ((tag, tagProperties, len (self.commandList)+1))
852 else:
853 self.tagStack.append ((tag, tagProperties, None))
854 else:
855 self.tagStack.append ((tag, tagProperties, None))
856 if (command is not None):
857 # All tags that have a TAL attribute on them start with a 'start scope'
858 self.addCommand((TAL_START_SCOPE, (originalAtts, tag[1])))
859 # Now we add the TAL command
860 self.addCommand(command)
861 else:
862 # It's just a straight output, so create an output command and append it
863 self.addCommand((TAL_OUTPUT, self.tagAsText (tag, singletonTag)))
864
865 def popTag (self, tag, omitTagFlag=0):
866 """ omitTagFlag is used to control whether the end tag should be included in the
867 output or not. In HTML 4.01 there are several tags which should never have
868 end tags, this flag allows the template compiler to specify that these
869 should not be output.
870 """
871 while (len (self.tagStack) > 0):
872 oldTag, tagProperties, useMacroLocation = self.tagStack.pop()
873 endTagSymbol = tagProperties.get ('endTagSymbol', None)
874 popCommandList = tagProperties.get ('popFunctionList', [])
875 singletonTag = tagProperties.get ('singletonTag', 0)
876 for func in popCommandList:
877 func()
878 self.log.debug ("Popped tag %s off stack" % oldTag[0])
879 if (oldTag[0] == tag[0]):
880 # We've found the right tag, now check to see if we have any TAL commands on it
881 if (endTagSymbol is not None):
882 # We have a command (it's a TAL tag)
883 # Note where the end tag symbol should point (i.e. the next command)
884 self.symbolLocationTable [endTagSymbol] = len (self.commandList)
885
886 # We need a "close scope and tag" command
887 self.addCommand((TAL_ENDTAG_ENDSCOPE, (tag[0], omitTagFlag, singletonTag)))
888 return
889 elif (omitTagFlag == 0 and singletonTag == 0):
890 # We are popping off an un-interesting tag, just add the close as text
891 self.addCommand((TAL_OUTPUT, '</' + tag[0] + '>'))
892 return
893 else:
894 # We are suppressing the output of this tag, so just return
895 return
896 else:
897 # We have a different tag, which means something like <br> which never closes is in
898 # between us and the real tag.
899
900 # If the tag that we did pop off has a command though it means un-balanced TAL tags!
901 if (endTagSymbol is not None):
902 # ERROR
903 msg = "TAL/METAL Elements must be balanced - found close tag %s expecting %s" % (tag[0], oldTag[0])
904 self.log.error (msg)
905 raise TemplateParseException (self.tagAsText(oldTag), msg)
906 self.log.error ("Close tag %s found with no corresponding open tag." % tag[0])
907 raise TemplateParseException ("</%s>" % tag[0], "Close tag encountered with no corresponding open tag.")
908
909 def parseStartTag (self, tag, attributes, singletonElement=0):
910 # Note down the tag we are handling, it will be used for error handling during
911 # compilation
912 self.currentStartTag = (tag, attributes)
913
914 # Look for tal/metal attributes
915 foundTALAtts = []
916 foundMETALAtts = []
917 foundCommandsArgs = {}
918 cleanAttributes = []
919 originalAttributes = {}
920 tagProperties = {}
921 popTagFuncList = []
922 TALElementNameSpace = 0
923 prefixToAdd = ""
924 tagProperties ['singletonTag'] = singletonElement
925
926 # Determine whether this element is in either the METAL or TAL namespace
927 if (tag.find (':') > 0):
928 # We have a namespace involved, so let's look to see if its one of ours
929 namespace = tag[0:tag.find (':')]
930 if (namespace == self.metal_namespace_prefix):
931 TALElementNameSpace = 1
932 prefixToAdd = self.metal_namespace_prefix +":"
933 elif (namespace == self.tal_namespace_prefix):
934 TALElementNameSpace = 1
935 prefixToAdd = self.tal_namespace_prefix +":"
936
937 if (TALElementNameSpace):
938 # We should treat this an implicit omit-tag
939 foundTALAtts.append (TAL_OMITTAG)
940 # Will go to default, i.e. yes
941 foundCommandsArgs [TAL_OMITTAG] = ""
942
943 for att, value in attributes:
944 originalAttributes [att] = value
945 if (TALElementNameSpace and not att.find (':') > 0):
946 # This means that the attribute name does not have a namespace, so use the prefix for this tag.
947 commandAttName = prefixToAdd + att
948 else:
949 commandAttName = att
950 self.log.debug ("Command name is now %s" % commandAttName)
951 if (att[0:5] == "xmlns"):
952 # We have a namespace declaration.
953 prefix = att[6:]
954 if (value == METAL_NAME_URI):
955 # It's a METAL namespace declaration
956 if (len (prefix) > 0):
957 self.metal_namespace_prefix_stack.append (self.metal_namespace_prefix)
958 self.setMETALPrefix (prefix)
959 # We want this function called when the scope ends
960 popTagFuncList.append (self.popMETALNamespace)
961 else:
962 # We don't allow METAL/TAL to be declared as a default
963 msg = "Can not use METAL name space by default, a prefix must be provided."
964 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
965 elif (value == TAL_NAME_URI):
966 # TAL this time
967 if (len (prefix) > 0):
968 self.tal_namespace_prefix_stack.append (self.tal_namespace_prefix)
969 self.setTALPrefix (prefix)
970 # We want this function called when the scope ends
971 popTagFuncList.append (self.popTALNamespace)
972 else:
973 # We don't allow METAL/TAL to be declared as a default
974 msg = "Can not use TAL name space by default, a prefix must be provided."
975 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
976 else:
977 # It's nothing special, just an ordinary namespace declaration
978 cleanAttributes.append ((att, value))
979 elif (commandAttName in self.tal_attribute_map):
980 # It's a TAL attribute
981 cmnd = self.tal_attribute_map [commandAttName]
982 if (cmnd == TAL_OMITTAG and TALElementNameSpace):
983 self.log.warning ("Supressing omit-tag command present on TAL or METAL element")
984 else:
985 foundCommandsArgs [cmnd] = value
986 foundTALAtts.append (cmnd)
987 elif (commandAttName in self.metal_attribute_map):
988 # It's a METAL attribute
989 cmnd = self.metal_attribute_map [commandAttName]
990 foundCommandsArgs [cmnd] = value
991 foundMETALAtts.append (cmnd)
992 else:
993 cleanAttributes.append ((att, value))
994 tagProperties ['popFunctionList'] = popTagFuncList
995
996 # This might be just content
997 if ((len (foundTALAtts) + len (foundMETALAtts)) == 0):
998 # Just content, add it to the various stacks
999 self.addTag ((tag, cleanAttributes), tagProperties)
1000 return
1001
1002 # Create a symbol for the end of the tag - we don't know what the offset is yet
1003 self.endTagSymbol += 1
1004 tagProperties ['endTagSymbol'] = self.endTagSymbol
1005
1006 # Sort the METAL commands
1007 foundMETALAtts.sort()
1008 # Sort the tags by priority
1009 foundTALAtts.sort()
1010
1011 # We handle the METAL before the TAL
1012 allCommands = foundMETALAtts + foundTALAtts
1013 firstTag = 1
1014 for talAtt in allCommands:
1015 # Parse and create a command for each
1016 cmnd = self.commandHandler [talAtt](foundCommandsArgs[talAtt])
1017 if (cmnd is not None):
1018 if (firstTag):
1019 # The first one needs to add the tag
1020 firstTag = 0
1021 tagProperties ['originalAtts'] = originalAttributes
1022 tagProperties ['command'] = cmnd
1023 self.addTag ((tag, cleanAttributes), tagProperties)
1024 else:
1025 # All others just append
1026 self.addCommand(cmnd)
1027
1028 if (firstTag):
1029 tagProperties ['originalAtts'] = originalAttributes
1030 tagProperties ['command'] = (TAL_STARTTAG, (tag, singletonElement))
1031 self.addTag ((tag, cleanAttributes), tagProperties)
1032 else:
1033 # Add the start tag command in as a child of the last TAL command
1034 self.addCommand((TAL_STARTTAG, (tag,singletonElement)))
1035
1036 def parseEndTag (self, tag):
1037 """ Just pop the tag and related commands off the stack. """
1038 self.popTag ((tag,None))
1039
1040 def parseData (self, data):
1041 # Just add it as an output
1042 self.addCommand((TAL_OUTPUT, data))
1043
1044 def compileCmdDefine (self, argument):
1045 # Compile a define command, resulting argument is:
1046 # [(isLocalFlag (Y/n), variableName, variablePath),...]
1047 # Break up the list of defines first
1048 commandArgs = []
1049 # We only want to match semi-colons that are not escaped
1050 argumentSplitter = re.compile ('(?<!;);(?!;)')
1051 for defineStmt in argumentSplitter.split (argument):
1052 # remove any leading space and un-escape any semi-colons
1053 defineStmt = defineStmt.lstrip().replace (';;', ';')
1054 # Break each defineStmt into pieces "[local|global] varName expression"
1055 stmtBits = defineStmt.split (' ')
1056 isLocal = 1
1057 if (len (stmtBits) < 2):
1058 # Error, badly formed define command
1059 msg = "Badly formed define command '%s'. Define commands must be of the form: '[local|global] varName expression[;[local|global] varName expression]'" % argument
1060 self.log.error (msg)
1061 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1062 # Assume to start with that >2 elements means a local|global flag
1063 if (len (stmtBits) > 2):
1064 if (stmtBits[0] == 'global'):
1065 isLocal = 0
1066 varName = stmtBits[1]
1067 expression = ' '.join (stmtBits[2:])
1068 elif (stmtBits[0] == 'local'):
1069 varName = stmtBits[1]
1070 expression = ' '.join (stmtBits[2:])
1071 else:
1072 # Must be a space in the expression that caused the >3 thing
1073 varName = stmtBits[0]
1074 expression = ' '.join (stmtBits[1:])
1075 else:
1076 # Only two bits
1077 varName = stmtBits[0]
1078 expression = ' '.join (stmtBits[1:])
1079
1080 commandArgs.append ((isLocal, varName, expression))
1081 return (TAL_DEFINE, commandArgs)
1082
1083 def compileCmdCondition (self, argument):
1084 # Compile a condition command, resulting argument is:
1085 # path, endTagSymbol
1086 # Sanity check
1087 if (len (argument) == 0):
1088 # No argument passed
1089 msg = "No argument passed! condition commands must be of the form: 'path'"
1090 self.log.error (msg)
1091 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1092
1093 return (TAL_CONDITION, (argument, self.endTagSymbol))
1094
1095 def compileCmdRepeat (self, argument):
1096 # Compile a repeat command, resulting argument is:
1097 # (varname, expression, endTagSymbol)
1098 attProps = argument.split (' ')
1099 if (len (attProps) < 2):
1100 # Error, badly formed repeat command
1101 msg = "Badly formed repeat command '%s'. Repeat commands must be of the form: 'localVariable path'" % argument
1102 self.log.error (msg)
1103 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1104
1105 varName = attProps [0]
1106 expression = " ".join (attProps[1:])
1107 return (TAL_REPEAT, (varName, expression, self.endTagSymbol))
1108
1109 def compileCmdContent (self, argument, replaceFlag=0):
1110 # Compile a content command, resulting argument is
1111 # (replaceFlag, structureFlag, expression, endTagSymbol)
1112
1113 # Sanity check
1114 if (len (argument) == 0):
1115 # No argument passed
1116 msg = "No argument passed! content/replace commands must be of the form: 'path'"
1117 self.log.error (msg)
1118 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1119
1120 structureFlag = 0
1121 attProps = argument.split (' ')
1122 if (len(attProps) > 1):
1123 if (attProps[0] == "structure"):
1124 structureFlag = 1
1125 express = " ".join (attProps[1:])
1126 elif (attProps[1] == "text"):
1127 structureFlag = 0
1128 express = " ".join (attProps[1:])
1129 else:
1130 # It's not a type selection after all - assume it's part of the path
1131 express = argument
1132 else:
1133 express = argument
1134 return (TAL_CONTENT, (replaceFlag, structureFlag, express, self.endTagSymbol))
1135
1136 def compileCmdReplace (self, argument):
1137 return self.compileCmdContent (argument, replaceFlag=1)
1138
1139 def compileCmdAttributes (self, argument):
1140 # Compile tal:attributes into attribute command
1141 # Argument: [(attributeName, expression)]
1142
1143 # Break up the list of attribute settings first
1144 commandArgs = []
1145 # We only want to match semi-colons that are not escaped
1146 argumentSplitter = re.compile ('(?<!;);(?!;)')
1147 for attributeStmt in argumentSplitter.split (argument):
1148 # remove any leading space and un-escape any semi-colons
1149 attributeStmt = attributeStmt.lstrip().replace (';;', ';')
1150 # Break each attributeStmt into name and expression
1151 stmtBits = attributeStmt.split (' ')
1152 if (len (stmtBits) < 2):
1153 # Error, badly formed attributes command
1154 msg = "Badly formed attributes command '%s'. Attributes commands must be of the form: 'name expression[;name expression]'" % argument
1155 self.log.error (msg)
1156 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1157 attName = stmtBits[0]
1158 attExpr = " ".join (stmtBits[1:])
1159 commandArgs.append ((attName, attExpr))
1160 return (TAL_ATTRIBUTES, commandArgs)
1161
1162 def compileCmdOmitTag (self, argument):
1163 # Compile a condition command, resulting argument is:
1164 # path
1165 # If no argument is given then set the path to default
1166 if (len (argument) == 0):
1167 expression = "default"
1168 else:
1169 expression = argument
1170 return (TAL_OMITTAG, expression)
1171
1172 # METAL compilation commands go here
1173 def compileMetalUseMacro (self, argument):
1174 # Sanity check
1175 if (len (argument) == 0):
1176 # No argument passed
1177 msg = "No argument passed! use-macro commands must be of the form: 'use-macro: path'"
1178 self.log.error (msg)
1179 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1180 cmnd = (METAL_USE_MACRO, (argument, {}, self.endTagSymbol))
1181 self.log.debug ("Returning METAL_USE_MACRO: %s" % str (cmnd))
1182 return cmnd
1183
1184 def compileMetalDefineMacro (self, argument):
1185 if (len (argument) == 0):
1186 # No argument passed
1187 msg = "No argument passed! define-macro commands must be of the form: 'define-macro: name'"
1188 self.log.error (msg)
1189 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1190
1191 # Check that the name of the macro is valid
1192 if (METAL_NAME_REGEX.match (argument).end() != len (argument)):
1193 msg = "Macro name %s is invalid." % argument
1194 self.log.error (msg)
1195 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1196 if (argument in self.macroMap):
1197 msg = "Macro name %s is already defined!" % argument
1198 self.log.error (msg)
1199 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1200
1201 # The macro starts at the next command.
1202 macro = SubTemplate (len (self.commandList), self.endTagSymbol)
1203 self.macroMap [argument] = macro
1204 return None
1205
1206 def compileMetalFillSlot (self, argument):
1207 if (len (argument) == 0):
1208 # No argument passed
1209 msg = "No argument passed! fill-slot commands must be of the form: 'fill-slot: name'"
1210 self.log.error (msg)
1211 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1212
1213 # Check that the name of the macro is valid
1214 if (METAL_NAME_REGEX.match (argument).end() != len (argument)):
1215 msg = "Slot name %s is invalid." % argument
1216 self.log.error (msg)
1217 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1218
1219 # Determine what use-macro statement this belongs to by working through the list backwards
1220 ourMacroLocation = None
1221 location = len (self.tagStack) - 1
1222 while (ourMacroLocation is None):
1223 macroLocation = self.tagStack[location][2]
1224 if (macroLocation is not None):
1225 ourMacroLocation = macroLocation
1226 else:
1227 location -= 1
1228 if (location < 0):
1229 msg = "metal:fill-slot must be used inside a metal:use-macro call"
1230 self.log.error (msg)
1231 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1232
1233 # Get the use-macro command we are going to adjust
1234 cmnd, args = self.commandList [ourMacroLocation]
1235 self.log.debug ("Use macro argument: %s" % str (args))
1236 macroName, slotMap, endSymbol = args
1237
1238 # Check that the name of the slot is valid
1239 if (METAL_NAME_REGEX.match (argument).end() != len (argument)):
1240 msg = "Slot name %s is invalid." % argument
1241 self.log.error (msg)
1242 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1243
1244 if (argument in slotMap):
1245 msg = "Slot %s has already been filled!" % argument
1246 self.log.error (msg)
1247 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1248
1249 # The slot starts at the next command.
1250 slot = SubTemplate (len (self.commandList), self.endTagSymbol)
1251 slotMap [argument] = slot
1252
1253 # Update the command
1254 self.commandList [ourMacroLocation] = (cmnd, (macroName, slotMap, endSymbol))
1255 return None
1256
1257 def compileMetalDefineSlot (self, argument):
1258 if (len (argument) == 0):
1259 # No argument passed
1260 msg = "No argument passed! define-slot commands must be of the form: 'name'"
1261 self.log.error (msg)
1262 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1263 # Check that the name of the slot is valid
1264 if (METAL_NAME_REGEX.match (argument).end() != len (argument)):
1265 msg = "Slot name %s is invalid." % argument
1266 self.log.error (msg)
1267 raise TemplateParseException (self.tagAsText (self.currentStartTag), msg)
1268
1269 return (METAL_DEFINE_SLOT, (argument, self.endTagSymbol))
1270
1271 class TemplateParseException (Exception):
1272 def __init__ (self, location, errorDescription):
1273 self.location = location
1274 self.errorDescription = errorDescription
1275
1276 def __str__ (self):
1277 return "[" + self.location + "] " + self.errorDescription
1278
1279
1280 class HTMLTemplateCompiler (TemplateCompiler, FixedHTMLParser.HTMLParser):
1281 def __init__ (self):
1282 TemplateCompiler.__init__ (self)
1283 FixedHTMLParser.HTMLParser.__init__ (self)
1284 self.log = logging.getLogger ("simpleTAL.HTMLTemplateCompiler")
1285
1286 def parseTemplate (self, file, minimizeBooleanAtts = False):
1287 self.minimizeBooleanAtts = minimizeBooleanAtts
1288 self.feed (file.read())
1289 self.close()
1290
1291 def tagAsText (self, tagObj, singletonFlag=0):
1292 """ This returns a tag as text.
1293 """
1294 tag,atts = tagObj
1295 result = ["<"]
1296 result.append (tag)
1297 upperTag = tag.upper()
1298 for attName, attValue in atts:
1299 if (self.minimizeBooleanAtts and '%s:%s' % (upperTag, attName.upper()) in HTML_BOOLEAN_ATTS):
1300 # We should output a minimised boolean value
1301 result.append (' ')
1302 result.append (attName)
1303 else:
1304 result.append (' ')
1305 result.append (attName)
1306 result.append ('="')
1307 result.append (html.escape (attValue, quote=1))
1308 result.append ('"')
1309 if (singletonFlag):
1310 result.append (" />")
1311 else:
1312 result.append (">")
1313 return "".join (result)
1314
1315 def handle_startendtag (self, tag, attributes):
1316 self.handle_starttag (tag, attributes)
1317 if not (tag.upper() in HTML_FORBIDDEN_ENDTAG):
1318 self.handle_endtag(tag)
1319
1320 def handle_starttag (self, tag, attributes):
1321 self.log.debug ("Received Start Tag: " + tag + " Attributes: " + str (attributes))
1322 atts = []
1323 for att, attValue in attributes:
1324 # We need to spot empty tal:omit-tags
1325 if (attValue is None):
1326 if (att == self.tal_namespace_omittag):
1327 atts.append ((att, ""))
1328 else:
1329 atts.append ((att, att))
1330 elif not HTML_ENTITIES_PRE_EXPANDED:
1331 # Expand any SGML entity references or char references
1332 goodAttValue = []
1333 last = 0
1334 match = ENTITY_REF_REGEX.search (attValue)
1335 while (match):
1336 goodAttValue.append (attValue[last:match.start()])
1337 ref = attValue[match.start():match.end()]
1338 if (ref.startswith ('&#')):
1339 # A char reference
1340 if (ref[2] in ['x', 'X']):
1341 # Hex
1342 refValue = int (ref[3:-1], 16)
1343 else:
1344 refValue = int (ref[2:-1])
1345 goodAttValue.append (chr (refValue))
1346 else:
1347 # A named reference.
1348 goodAttValue.append (chr (sgmlentitynames.htmlNameToUnicodeNumber.get (ref[1:-1], 65533)))
1349 last = match.end()
1350 match = ENTITY_REF_REGEX.search (attValue, last)
1351 goodAttValue.append (attValue [last:])
1352 atts.append ((att, "".join (goodAttValue)))
1353 else:
1354 atts.append ((att, attValue))
1355
1356 if (tag.upper() in HTML_FORBIDDEN_ENDTAG):
1357 # This should have no end tag, so we just do the start and suppress the end
1358 self.parseStartTag (tag, atts)
1359 self.log.debug ("End tag forbidden, generating close tag with no output.")
1360 self.popTag ((tag, None), omitTagFlag=1)
1361 else:
1362 self.parseStartTag (tag, atts)
1363
1364 def handle_endtag (self, tag):
1365 self.log.debug ("Recieved End Tag: " + tag)
1366 if (tag.upper() in HTML_FORBIDDEN_ENDTAG):
1367 self.log.warning ("HTML 4.01 forbids end tags for the %s element" % tag)
1368 else:
1369 # Normal end tag
1370 self.popTag ((tag, None))
1371
1372 def handle_data (self, data):
1373 self.parseData (html.escape (data, quote=False))
1374
1375 # These two methods are required so that we expand all character and entity references prior to parsing the template.
1376 def handle_charref (self, ref):
1377 self.log.debug ("Got Ref: %s", ref)
1378 self.parseData (chr (int (ref)))
1379
1380 def handle_entityref (self, ref):
1381 self.log.debug ("Got Ref: %s", ref)
1382 # Use handle_data so that <&> are re-encoded as required.
1383 self.handle_data( chr (sgmlentitynames.htmlNameToUnicodeNumber.get (ref, 65533)))
1384
1385 # Handle document type declarations
1386 def handle_decl (self, data):
1387 self.parseData ('<!%s>' % data)
1388
1389 # Pass comments through un-affected.
1390 def handle_comment (self, data):
1391 self.parseData ('<!--%s-->' % data)
1392
1393 def handle_pi (self, data):
1394 self.log.debug ("Recieved processing instruction.")
1395 self.parseData ('<?%s>' % data)
1396
1397 def report_unbalanced (self, tag):
1398 self.log.warning ("End tag %s present with no corresponding open tag.")
1399
1400 def getTemplate (self):
1401 template = HTMLTemplate (self.commandList, self.macroMap, self.symbolLocationTable, minimizeBooleanAtts = self.minimizeBooleanAtts)
1402 return template
1403
1404 class XMLTemplateCompiler (TemplateCompiler, xml.sax.handler.ContentHandler, xml.sax.handler.DTDHandler, LexicalHandler):
1405 def __init__ (self):
1406 TemplateCompiler.__init__ (self)
1407 xml.sax.handler.ContentHandler.__init__ (self)
1408 self.doctype = None
1409 self.log = logging.getLogger ("simpleTAL.XMLTemplateCompiler")
1410 self.singletonElement = 0
1411
1412 def parseTemplate (self, templateFile):
1413 self.ourParser = xml.sax.make_parser()
1414 self.log.debug ("Setting features of parser")
1415 try:
1416 self.ourParser.setFeature (xml.sax.handler.feature_external_ges, False)
1417 self.log.debug ("Set SAX Handler feature OK")
1418 except:
1419 pass
1420 if use_lexical_handler:
1421 self.ourParser.setProperty(xml.sax.handler.property_lexical_handler, self)
1422
1423 self.ourParser.setContentHandler (self)
1424 self.ourParser.setDTDHandler (self)
1425
1426 self.ourParser.parse (templateFile)
1427
1428 def startDTD(self, name, public_id, system_id):
1429 self.log.debug ("Recieved DOCTYPE: " + name + " public_id: " + public_id + " system_id: " + system_id)
1430 if public_id:
1431 self.doctype = '<!DOCTYPE %s PUBLIC "%s" "%s">' % (name, public_id, system_id,)
1432 else:
1433 self.doctype = '<!DOCTYPE %s SYSTEM "%s">' % (name, system_id,)
1434
1435 def startElement (self, tag, attributes):
1436 self.log.debug ("Recieved Real Start Tag: " + tag + " Attributes: " + str (attributes))
1437 try:
1438 xmlText = self.ourParser.getProperty (xml.sax.handler.property_xml_string)
1439 if (isinstance (xmlText, str)):
1440 # Once issue 6686 is solved this should allow singletons to be detected
1441 if (SINGLETON_XML_REGEX.match (xmlText)):
1442 # This is a singleton!
1443 self.singletonElement=1
1444 else:
1445 if (SINGLETON_BYTES_XML_REGEX.match (xmlText)):
1446 # This is a singleton!
1447 self.singletonElement = 1
1448 except xml.sax.SAXException as e:
1449 # Parser doesn't support this property
1450 pass
1451 # Convert attributes into a list of tuples
1452 atts = []
1453 for att in attributes.getNames():
1454 self.log.debug ("Attribute name %s has value %s" % (att, attributes[att]))
1455 atts.append ((att, attributes [att]))
1456 self.parseStartTag (tag, atts, singletonElement=self.singletonElement)
1457
1458 def endElement (self, tag):
1459 self.log.debug ("Recieved Real End Tag: " + tag)
1460 self.parseEndTag (tag)
1461 self.singletonElement = 0
1462
1463 def skippedEntity (self, name):
1464 self.log.info ("Recieved skipped entity: %s" % name)
1465 self.characters( chr (sgmlentitynames.htmlNameToUnicodeNumber.get (name, 65533)))
1466
1467 def characters (self, data):
1468 #self.log.debug ("Recieved Real Data: " + data)
1469 # Escape any data we recieve - we don't want any: <&> in there.
1470 self.parseData (html.escape (data, quote=False))
1471
1472 def processingInstruction (self, target, data):
1473 self.log.debug ("Recieved processing instruction.")
1474 self.parseData ('<?%s %s?>' % (target, data))
1475
1476 def comment (self, data):
1477 # This is only called if your XML parser supports the LexicalHandler interface.
1478 self.parseData ('<!--%s-->' % data)
1479
1480 def getTemplate (self):
1481 template = XMLTemplate (self.commandList, self.macroMap, self.symbolLocationTable, self.doctype)
1482 return template
1483
1484 def compileHTMLTemplate (template, minimizeBooleanAtts = 0):
1485 """ Reads the templateFile and produces a compiled template.
1486 To use the resulting template object call:
1487 template.expand (context, outputFile)
1488 """
1489 if (isinstance (template, str)):
1490 # It's a string!
1491 templateFile = io.StringIO (template)
1492 else:
1493 templateFile = template
1494 compiler = HTMLTemplateCompiler()
1495 compiler.parseTemplate (templateFile, minimizeBooleanAtts)
1496 return compiler.getTemplate()
1497
1498 def compileXMLTemplate (template):
1499 """ Reads the templateFile and produces a compiled template.
1500 To use the resulting template object call:
1501 template.expand (context, outputFile)
1502 """
1503 if (isinstance (template, str)):
1504 # It's a string!
1505 templateFile = io.StringIO (template)
1506 elif (isinstance (template, bytes)):
1507 templateFile = io.BytesIO (template)
1508 else:
1509 templateFile = template
1510 compiler = XMLTemplateCompiler()
1511 compiler.parseTemplate (templateFile)
1512 return compiler.getTemplate()