def simpletal(dirname, verbose=False): try: from simpletal import simpleTAL, simpleTALES except ImportError: print>>sys.stderr, "SimpleTAL not installed, skipping" return lambda: None fileobj = open(os.path.join(dirname, 'base.html')) base = simpleTAL.compileHTMLTemplate(fileobj) fileobj.close() fileobj = open(os.path.join(dirname, 'template.html')) template = simpleTAL.compileHTMLTemplate(fileobj) fileobj.close() def render(): ctxt = simpleTALES.Context(allowPythonPath=1) ctxt.addGlobal('base', base) ctxt.addGlobal('title', 'Just a test') ctxt.addGlobal('user', 'joe') ctxt.addGlobal('items', ['Number %d' % num for num in range(1, 15)]) buf = StringIO() template.expand(ctxt, buf) return buf.getvalue() if verbose: print render() return render
def simpletal(dirname, verbose=False): try: from simpletal import simpleTAL, simpleTALES except ImportError: print("SimpleTAL not installed, skipping") return lambda: None fileobj = open(os.path.join(dirname, 'base.html')) base = simpleTAL.compileHTMLTemplate(fileobj) fileobj.close() fileobj = open(os.path.join(dirname, 'template.html')) template = simpleTAL.compileHTMLTemplate(fileobj) fileobj.close() def render(): ctxt = simpleTALES.Context(allowPythonPath=1) ctxt.addGlobal('base', base) ctxt.addGlobal('title', 'Just a test') ctxt.addGlobal('user', 'joe') ctxt.addGlobal('items', ['Number %d' % num for num in range(1, 15)]) buf = StringIO() template.expand(ctxt, buf) return buf.getvalue() if verbose: print(render()) return render
def prepare(self, **options): from simpletal import simpleTAL # TODO: add option to load METAL files during render if self.source: self.tpl = simpleTAL.compileHTMLTemplate(self.source) else: with open(self.filename, 'rb') as fp: self.tpl = simpleTAL.compileHTMLTemplate(utils.tonat(fp.read()))
def writeScheme(units = [], scheme_title = None, out_file_name = None, all_file_titles_names = [], sid = None ): """Produce the actual HTML file for each set, using the template and units given""" # all the variables for the template will go in here glob = {} glob['scheme_title'] = scheme_title glob['other_schemes'] = [ {'title' : t, 'filename' : f, 'selected' : t==scheme_title and 'selected' or '' } for (t,f) in all_file_titles_names] half_terms = [] for ht in csv.DictReader(open("config/HalfTerms.csv")): half_terms.append( { 'number': ht['half_term'], 'title' : ht['long_title'], 'weeks' : ht['weeks'], 'code' : ht['code'], 'units' : [u for u in units if str(u['ht']) == ht['half_term'] ], } ) glob['half_terms']= half_terms context = simpleTALES.Context(allowPythonPath = 1) for (k, v) in glob.items(): context.addGlobal(k,v) template_file = open("templates/details.html") template = simpleTAL.compileHTMLTemplate(template_file) template_file.close() out_file = open(out_file_name, 'w') template.expand(context, out_file, outputEncoding="utf-8") out_file.close() template_file = open("templates/cards.html") template = simpleTAL.compileHTMLTemplate(template_file) template_file.close() cards_filename = out_file_name.replace("scheme-", "cards-") cards_file = open(cards_filename, 'w') template.expand(context, cards_file , outputEncoding="utf-8") cards_file.close() template_file = open("templates/booklet.html") template = simpleTAL.compileHTMLTemplate(template_file) template_file.close() cards_filename = out_file_name.replace("scheme-", "booklet-") cards_file = open(cards_filename, 'w') template.expand(context, cards_file , outputEncoding="utf-8") cards_file.close()
def prepare(self, **options): from simpletal import simpleTAL # TODO: add option to load METAL files during render if self.source: self.tpl = simpleTAL.compileHTMLTemplate(self.source) else: with open(self.filename, 'rb') as fp: self.tpl = simpleTAL.compileHTMLTemplate(utils.tonat( fp.read()))
def prepare(self, **options): depr('The SimpleTAL template handler is deprecated'\ ' and will be removed in 0.12') from simpletal import simpleTAL if self.source: self.tpl = simpleTAL.compileHTMLTemplate(self.source) else: with open(self.filename, 'rb') as fp: self.tpl = simpleTAL.compileHTMLTemplate(tonat(fp.read()))
def _runTest_ (self, macros, page, result, errMsg="Error"): macroTemplate = simpleTAL.compileHTMLTemplate (macros) #print "Macro template: " + str (macroTemplate) pageTemplate = simpleTAL.compileHTMLTemplate (page) self.context.addGlobal ("site", macroTemplate) self.context.addGlobal ("here", pageTemplate) file = io.StringIO () pageTemplate.expand (self.context, file) realResult = file.getvalue() self.failUnless (realResult == result, "%s - \npassed in macro: %s \npage: %s\ngot back %s \nexpected %s\n" % (errMsg, macros, page, realResult, result))
def _runTest_ (self, macros, page, result, errMsg="Error"): macroTemplate = simpleTAL.compileHTMLTemplate (macros) #print "Macro template: " + str (macroTemplate) pageTemplate = simpleTAL.compileHTMLTemplate (page) self.context.addGlobal ("site", macroTemplate) self.context.addGlobal ("here", pageTemplate) file = io.StringIO () pageTemplate.expand (self.context, file) realResult = file.getvalue() self.assertTrue (realResult == result, "%s - \npassed in macro: %s \npage: %s\ngot back %s \nexpected %s\n" % (errMsg, macros, page, realResult, result))
def apply_to(view, obj, refpkg=None): f = view.content_as_file html = view.content_mimetype.startswith("text/html") if html: t = simpleTAL.compileHTMLTemplate(f, "utf-8") kw = {} else: t = simpleTAL.compileXMLTemplate(f) kw = { "suppressXMLDeclaration": 1 } # It is a bit ugly to suppress XML declaration, but necessary when XML # views are used inside other XML views. # Furthermore, this does not seem to serious a ugliness, since we use # UTF-8 # encoding, which appears to be the default (at least for # simpleTAL generator), and since the XML spec allows well-formed # documents to have no XML declaration. f.close() # should we cache the compiled template for future uses, # and recompile it only when the content is modified? # the problem is that external contents may be modified without notification # (or rely on f.headers['date'], but that would require to hack content.py # to make that field *always* present - might be a good idea...) c = AdveneContext(here=obj) c.addGlobal("view", view) if refpkg is None: if hasattr(obj, "ADVENE_TYPE"): refpkg = obj.owner else: refpkg = obj c.addGlobal("package", refpkg) out = StringIO() t.expand(c, out, outputEncoding="utf-8", **kw) return out.getvalue()
def testUTF8ToISO (self): template = simpleTAL.compileHTMLTemplate (b'<html>\xc2\xa33.12? <b tal:replace="HighBC"></b></html>'.decode ('utf-8')) file = io.StringIO() template.expand (self.context, file) result = file.getvalue() expectedResult = "<html>�12? This cost nothing, yep �</html>" self.failUnless (result == expectedResult, "UTF8 -> ISO Encoding failed. \nResult was: " + result + "\nExpected result: " + expectedResult)
def _runCompileTest_ (self, txt, result, errMsg="Error"): try: macroTemplate = simpleTAL.compileHTMLTemplate (txt) except simpleTAL.TemplateParseException as e: self.assertTrue (str (e) == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, str(e), result, pageTemplate)) return self.fail ("Expected exception '%s' during compile - but got no exception" % result)
def testMacroExpansionSlots(self): txt = '<html><div metal:use-macro="mac/macros/one">Hello<b metal:fill-slot="blue">Blue</b></div></html>' template = simpleTAL.compileHTMLTemplate(txt) self._runTest_( template, txt, '<html><body metal:use-macro="mac/macros/one">World is <b metal:fill-slot="blue">Blue</b></body></html>', 'Expasion with slots failed.')
def testCompileTemplateBinary (self): """ Test creating an HTML template directly from a file that was binary opened. Write output to a binary file, letting simpleTAL do the encoding. """ # Create a temporary file, they auto-delete templateFile = tempfile.TemporaryFile (mode="w+b") # Write out the HTML in UTF-8 txt = '<html><p>Somethings cost £3</p><p tal:content="one">Two</p></html>' expectedOutput = '<html><p>Somethings cost £3</p><p>1</p></html>' templateFile.write (txt.encode ('utf-8')) templateFile.seek (0) # Wrap the file in a reader, and bring it back in. reader = codecs.lookup ("utf-8").streamreader(templateFile) template = simpleTAL.compileHTMLTemplate (reader) # Now expand the template into a destination file that is binary outputFile = tempfile.TemporaryFile (mode="w+b") template.expand (self.context,outputFile) # Read it back in and compare with what we expected outputFile.seek(0) outputValue = outputFile.read ().decode ('utf-8') self.assertTrue (outputValue == expectedOutput, "passed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, outputValue, expectedOutput, template))
def testCompileTemplateText (self): """ Test creating an HTML template directly from a file that was text opened. Write output to a text file, letting the caller do the encoding. """ # Create a temporary file manually try: fileName = tempfile.mktemp () with open (fileName, mode='t+w', encoding = "utf-8") as templateFile: # Write out the HTML in UTF-8 txt = '<html><p>Somethings cost £3</p><p tal:content="one">Two</p></html>' expectedOutput = '<html><p>Somethings cost £3</p><p>1</p></html>' templateFile.write (txt) templateFile.seek (0) template = simpleTAL.compileHTMLTemplate (templateFile) finally: # Delete the temporary file we created os.remove (fileName) try: fileName = tempfile.mktemp () with open (fileName, mode="t+w") as outputFile: # Now expand the template into a destination file that is binary template.expand (self.context,outputFile) # Read it back in and compare with what we expected outputFile.seek(0) outputValue = outputFile.read () finally: # Delete the temporary file we created os.remove (fileName) self.assertTrue (outputValue == expectedOutput, "passed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, outputValue, expectedOutput, template))
def testUTF8ToISO (self): template = simpleTAL.compileHTMLTemplate (b'<html>\xc2\xa33.12? <b tal:replace="HighBC"></b></html>'.decode ('utf-8')) file = io.StringIO() template.expand (self.context, file) result = file.getvalue() expectedResult = "<html>�12? This cost nothing, yep �</html>" self.assertTrue (result == expectedResult, "UTF8 -> ISO Encoding failed. \nResult was: " + result + "\nExpected result: " + expectedResult)
def _runCompileTest_ (self, txt, result, errMsg="Error"): try: macroTemplate = simpleTAL.compileHTMLTemplate (txt) except simpleTAL.TemplateParseException as e: self.failUnless (str (e) == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, str(e), result, pageTemplate)) return self.fail ("Expected exception '%s' during compile - but got no exception" % result)
def getpage(self, fields): """fields - dict of HTTP pears. Returns formatted page string, according to fields['job']""" job = fields.get('job') or 'view' # Creat the context that is used by the template context = simpleTALES.Context(allowPythonPath=1) context.addGlobal( "cfg", { 'version': Config.get('version'), 'link': Config.get('link'), 'logo': Config.get('logo'), 'css': Config.get('css') }) # Add objects into the template context context = getattr(self, "_context_" + job)(context, fields) # Open the template file templateFile = open( os.path.join(Config.get('zpt_path'), "".join([job, ".zpt"])), 'r') # Compile a template template = simpleTAL.compileHTMLTemplate(templateFile, self.encoding) # Close the template file templateFile.close() # Create fake file that lets print file as a string fastFile = simpleTALUtils.FastStringOutput() # Expand the template as HTML using this context template.expand(context, fastFile, self.encoding) return fastFile.getvalue() #yo people! it's ZPT content"
def _runCacheTest_ (self, txt, result, errMsg="Error"): template = simpleTAL.compileHTMLTemplate (txt) file = io.StringIO () template.expand (self.context, file) realResult = file.getvalue() self.assertTrue (realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template)) self.assertTrue (self.recorder.called == 1, 'Recorder shows function was called %s times!' % str (self.recorder.called))
def testCompileTemplateBinary(self): """ Test creating an HTML template directly from a file that was binary opened. Write output to a binary file, letting simpleTAL do the encoding. """ # Create a temporary file, they auto-delete templateFile = tempfile.TemporaryFile(mode="w+b") # Write out the HTML in UTF-8 txt = '<html><p>Somethings cost £3</p><p tal:content="one">Two</p></html>' expectedOutput = '<html><p>Somethings cost £3</p><p>1</p></html>' templateFile.write(txt.encode('utf-8')) templateFile.seek(0) # Wrap the file in a reader, and bring it back in. reader = codecs.lookup("utf-8").streamreader(templateFile) template = simpleTAL.compileHTMLTemplate(reader) # Now expand the template into a destination file that is binary outputFile = tempfile.TemporaryFile(mode="w+b") template.expand(self.context, outputFile) # Read it back in and compare with what we expected outputFile.seek(0) outputValue = outputFile.read().decode('utf-8') self.failUnless( outputValue == expectedOutput, "passed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (txt, outputValue, expectedOutput, template))
def _runTest2_ (self, txt, result, errMsg="Error"): macroTemplate = simpleTAL.compileHTMLTemplate (txt) self.context.addGlobal ("site", macroTemplate) file = io.StringIO () pageTemplate2.expand (self.context, file) realResult = file.getvalue() self.assertTrue (realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, pageTemplate))
def testMacroExpansionSlots (self): txt = '<html><div metal:use-macro="mac/macros/one">Hello<b metal:fill-slot="blue">Blue</b></div></html>' template = simpleTAL.compileHTMLTemplate (txt) self._runTest_ (template ,txt ,'<html><body metal:use-macro="mac/macros/one">World is <b metal:fill-slot="blue">Blue</b></body></html>' ,'Expasion with slots failed.')
def _runTest_ (self, txt, result, errMsg="Error", expectedRecorderVal=0): template = simpleTAL.compileHTMLTemplate (txt) file = io.StringIO () template.expand (self.context, file) realResult = file.getvalue() self.assertTrue (realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template)) self.assertTrue (self.recorder.called == expectedRecorderVal, 'Call recorder detected that the call recorder object has state %s' % str (self.recorder.called))
def testContentStructure (self): # This test uses a specific context entry = """Some structure: <b tal:content="weblog/subject"></b>""" weblog = {'subject': 'Test subject', 'entry': simpleTAL.compileHTMLTemplate(entry)} self.context.addGlobal ('weblog', weblog) self._runTest_ ('<html><p tal:replace="structure weblog/entry">Original</p></html>' ,'<html>Some structure: <b>Test subject</b></html>' ,'Content of Structure did not evaluate to expected result')
def _runTest_(self, txt, result, errMsg="Error"): template = simpleTAL.compileHTMLTemplate(txt) file = io.StringIO() template.expand(self.context, file) realResult = file.getvalue() self.failUnless( realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template))
def testUnbalancedCloseTag (self): try: template = simpleTAL.compileHTMLTemplate ("<p>Hello</b> World</p>") file = io.StringIO () template.expand (self.context, file) realResult = file.getvalue() self.fail ("No exception raised during parsing of unbalanced tag.") except simpleTAL.TemplateParseException as e: pass
def testUnicodeSubclass (self): if (oldPython): return template = simpleTAL.compileHTMLTemplate ('<html tal:content="inheritance"></html>') file = io.StringIO() template.expand (self.context, file) result = file.getvalue() expectedResult = "<html>\u2018subclass\u2019</html>" self.failUnless (result == expectedResult, "Unicode subclass failed. \nResult was: " + result + "\nExpected result: " + expectedResult)
def testUnicodeSubclass (self): if (oldPython): return template = simpleTAL.compileHTMLTemplate ('<html tal:content="inheritance"></html>') file = io.StringIO() template.expand (self.context, file) result = file.getvalue() expectedResult = "<html>\u2018subclass\u2019</html>" self.assertTrue (result == expectedResult, "Unicode subclass failed. \nResult was: " + result + "\nExpected result: " + expectedResult)
def render_text(self, view, context): """Renderes the TAL view using the context into plain text.""" source = open(self.path_for(view), 'r') template = simpleTAL.compileHTMLTemplate(source) source.close() text = StringIO.StringIO() template.expand(context, text, outputEncoding='utf-8') return unicode(text.getvalue(), 'utf-8')
def do_error(self, errorstr): from simpletal import simpleTAL, simpleTALES import sys context = simpleTALES.Context( ) templateFile = open ("%s/WebRoot/error.html"%(self.config['general.webroot']) , 'r') template = simpleTAL.compileHTMLTemplate (templateFile) templateFile.close() context.addGlobal ("error", errorstr) template.expand (context, sys.stdout) sys.exit()
def _runTest_ (self, txt, result, errMsg="Error"): template = simpleTAL.compileHTMLTemplate (txt) file = io.StringIO () try: template.expand (self.context, file) except Exception as e: print("Error, template compiled to: " + str (template)) raise e realResult = file.getvalue() self.assertTrue (realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template))
def testContentStructure (self): # This test has specific needs - i.e. wrap the weblog/entry in a template... entry = """Some structure: <b tal:content="weblog/subject"></b>""" entryTemplate = simpleTAL.compileHTMLTemplate(entry) weblog = {'subject': 'Test subject', 'entry': entryTemplate} self.context.addGlobal ('weblog', weblog) self._runTest_ ('<html><p tal:content="structure weblog/entry">Original</p></html>' ,'<html><p>Some structure: <b>Test subject</b></p></html>' ,'Content of Structure did not evaluate to expected result')
def testISOToUTF8 (self): utf8Pound = b"\xc2\xa3" # Test file is encoded in ISO-8859-1, so we can use literal characters for this test. template = simpleTAL.compileHTMLTemplate ('<html>�12? <b tal:replace="HighBC"></b></html>') file = io.StringIO() template.expand (self.context, file) result = file.getvalue() expectedResult = b"<html>" + utf8Pound + b"3.12? This cost nothing, yep " + utf8Pound + b"0!</html>" expectedResult = expectedResult.decode ("utf-8") self.failUnless (result == expectedResult, "UTF8 Encoding failed. \nResult was: " + result + "\nExpected result: " + expectedResult)
def testISOToUTF8 (self): utf8Pound = b"\xc2\xa3" # Test file is encoded in ISO-8859-1, so we can use literal characters for this test. template = simpleTAL.compileHTMLTemplate ('<html>�12? <b tal:replace="HighBC"></b></html>') file = io.StringIO() template.expand (self.context, file) result = file.getvalue() expectedResult = b"<html>" + utf8Pound + b"3.12? This cost nothing, yep " + utf8Pound + b"0!</html>" expectedResult = expectedResult.decode ("utf-8") self.assertTrue (result == expectedResult, "UTF8 Encoding failed. \nResult was: " + result + "\nExpected result: " + expectedResult)
def __getattr__(self, key): fq = os.path.join(self.path, key) if self.vfs.isfile(fq + ".html.tal"): templateFile = self.vfs.open(fq + ".html.tal") compiled = simpleTAL.compileHTMLTemplate(templateFile) templateFile.close() return compiled elif self.vfs.isdir(fq): return self.__class__(self.vfs, fq) else: raise AttributeError("Key %s not found in %s" % (key, self.path))
def _runErrTest_(self, txt, result, errMsg="Error"): try: template = simpleTAL.compileHTMLTemplate(txt) except simpleTAL.TemplateParseException as e: realResult = str(e) self.failUnless( realResult == result, "%s - \npassed in: %s \ngot back exception %s \nexpected exception %s\n" % (errMsg, txt, realResult, result)) return self.fail("No exception thrown!")
def __getattr__(self, key): fq = os.path.join(self.path, key) if self.vfs.isfile(fq + ".html.tal"): templateFile = self.vfs.open(fq + ".html.tal") compiled = simpleTAL.compileHTMLTemplate(templateFile) templateFile.close() return compiled elif self.vfs.isdir(fq): return self.__class__(self.vfs, fq) else: raise AttributeError, "Key %s not found in %s" % (key, self.path)
def testContentStructure(self): # This test has specific needs - i.e. wrap the weblog/entry in a template... entry = """Some structure: <b tal:content="weblog/subject"></b>""" entryTemplate = simpleTAL.compileHTMLTemplate(entry) weblog = {'subject': 'Test subject', 'entry': entryTemplate} self.context.addGlobal('weblog', weblog) self._runTest_( '<html><p tal:content="structure weblog/entry">Original</p></html>', '<html><p>Some structure: <b>Test subject</b></p></html>', 'Content of Structure did not evaluate to expected result')
def __getattr__(self, key): fq = os.path.join(self.path, key) if self.vfs.isfile(fq + ".html.tal"): with self.vfs.open(fq + ".html.tal", "r", errors="replace") as template_file: compiled = simpleTAL.compileHTMLTemplate(template_file) return compiled elif self.vfs.isdir(fq): return self.__class__(self.vfs, fq) else: raise AttributeError("Key %s not found in %s" % (key, self.path))
def loadPageTemplate(filename): """ Loads and compiles the page template """ #create the context that is used by the template context = simpleTALES.Context() #load and compile the page template templateFile = open(filename, 'rt') template = simpleTAL.compileHTMLTemplate(templateFile) templateFile.close() #load and compile the main template macro macroFile = open(MAIN_TEMPLATE_FILENAME, 'rt') mainTemplate = simpleTAL.compileHTMLTemplate(macroFile) macroFile.close() #add main template to context context.addGlobal("main_template", mainTemplate) #return context and page template return (context, template)
def _runTest_(self, txt, result, errMsg="Error", expectedRecorderVal=0): template = simpleTAL.compileHTMLTemplate(txt) file = io.StringIO() template.expand(self.context, file) realResult = file.getvalue() self.failUnless( realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template)) self.failUnless( self.recorder.called == expectedRecorderVal, 'Call recorder detected that the call recorder object has state %s' % str(self.recorder.called))
def load (self, k): template_path = os.path.join(self.templatedir, '%s.html' % k) template = simpleTAL.compileHTMLTemplate(open(template_path)) mtime = os.stat(template_path).st_mtime v = { 'name': k, 'path': template_path, 'mtime': mtime, 'template': template } self.cache[k] = v return v
def __init__(self, document, html_window=None, auto_refresh=False, do_import=True, name="html"): # init HTML string, wxWidget self.view = None self.auto_refresh = auto_refresh self.html_window = html_window # Create the context that is used by the template self.context = simpleTALES.Context(allowPythonPath=1) template_file = open (PREVIEW_PT, 'r') self.template = simpleTAL.compileHTMLTemplate(template_file, inputEncoding=ENCODING) template_file.close() # init view AbstractView.__init__(self, document, do_import, name)
def _runCacheTest_(self, txt, result, errMsg="Error"): template = simpleTAL.compileHTMLTemplate(txt) file = io.StringIO() template.expand(self.context, file) realResult = file.getvalue() self.failUnless( realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template)) self.failUnless( self.recorder.called == 1, 'Recorder shows function was called %s times!' % str(self.recorder.called))
def _runTest_(self, txt, result, errMsg="Error"): template = simpleTAL.compileHTMLTemplate(txt) file = io.StringIO() try: template.expand(self.context, file) except Exception as e: print("Error, template compiled to: " + str(template)) raise e realResult = file.getvalue() self.failUnless( realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template))
def __init__(self, desc, html_window=None, auto_refresh=False, do_import=True, name="html"): # init HTML string, wxWidget self.view = None self.auto_refresh = auto_refresh self.html_window = html_window and UIProxy(html_window) or None # Create the context that is used by the template self.context = simpleTALES.Context(allowPythonPath=1) template_file = open(PREVIEW_PT(), "r") self.template = simpleTAL.compileHTMLTemplate(template_file, inputEncoding=ENCODING) template_file.close() self.context.addGlobal("pseudo", desc.document.get_pseudo()) # init view AbstractView.__init__(self, desc, do_import, name) self._update_view()
def writeHTML(self): context = simpleTALES.Context(allowPythonPath=1) context.addGlobal('library', self) template_file = open("templates/index.html", encoding="utf-8") template = simpleTAL.compileHTMLTemplate(template_file) template_file.close() out_file = open(os.path.join(self.output_path, "index.html"), 'w', encoding="utf-8") template.expand(context, out_file, outputEncoding="utf-8") out_file.close() # make a separate details file for each allocated scheme for ascheme in self.getAllocatedSchemes(): context.addGlobal('thisascheme', ascheme) template_file = open("templates/details.html", encoding="utf-8") template = simpleTAL.compileHTMLTemplate(template_file) template_file.close() out_file = open(os.path.join(self.output_path, ascheme.getDetailsFileName()), 'w', encoding="utf-8") template.expand(context, out_file, outputEncoding="utf-8") out_file.close()
def expandTemplate (self, templateName, outputName, additionalContext = None, sorter=None): context = simpleTALES.Context() context.addGlobal (self.name, self.contextFactory.getContextMap (sorter)) if (additionalContext is not None): context.addGlobal (additionalContext[0], additionalContext[1]) if (self.template is None): templateFile = open (templateName, 'r') self.template = simpleTAL.compileHTMLTemplate (templateFile) templateFile.close() outputFile = open (outputName, 'w') self.template.expand (context, outputFile) outputFile.close()
def expandTemplate(self, templateName): # Print out the headers sys.stdout.write("Content-Type: text/html\n") # HTML is following sys.stdout.write("\n") # blank line, end of headers # Expand the template and print it out templateFile = open(templateName, 'rt', encoding="utf-8") template = simpleTAL.compileHTMLTemplate(templateFile) # Close the template file templateFile.close() # Expand the template as HTML using this context template.expand(self.context, sys.stdout) sys.exit(0)
def expandTemplate (self, templateName): # Print out the headers sys.stdout.write ("Content-Type: text/html\n") # HTML is following sys.stdout.write ("\n") # blank line, end of headers # Expand the template and print it out templateFile = open (templateName, 'rt', encoding = "utf-8") template = simpleTAL.compileHTMLTemplate (templateFile) # Close the template file templateFile.close() # Expand the template as HTML using this context template.expand (self.context, sys.stdout) sys.exit (0)
def _runTest_ (self, txt, result, errMsg="Error", allowPythonPath=0): self.context = simpleTALES.Context(allowPythonPath=allowPythonPath) self.context.addGlobal ('top', 'Hello from the top') self.context.addGlobal ('exceptFunc', exceptionalFunction) self.context.addGlobal ('helloFunc', simpleFunction) self.context.addGlobal ('helloPath', simpleTALES.PathFunctionVariable(simpleFunction)) self.context.addGlobal ('helloFunction', helloFunction) self.context.addGlobal ('myList', [1,2,3,4,5,6]) self.context.addGlobal ('testing', 'testing') self.context.addGlobal ('map', {'test': 'maptest'}) self.context.addGlobal ('data', {'one': 1, 'zero': 0}) template = simpleTAL.compileHTMLTemplate (txt) file = io.StringIO () template.expand (self.context, file) realResult = file.getvalue() self.assertTrue (realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template))
def write(self, wfile): rfile = self.vfs.open(self.getselector()) context = simpleTALES.Context(allowPythonPath = self.allowpythonpath) context.addGlobal("selector", self.getselector()) context.addGlobal('handler', self) context.addGlobal('entry', self.getentry()) context.addGlobal('talbasename', self.talbasename) context.addGlobal('allowpythonpath', self.allowpythonpath) context.addGlobal('protocol', self.protocol) context.addGlobal('root', TALLoader(self.vfs, '/')) context.addGlobal('rroot', RecursiveTALLoader(self.vfs, '/')) dirname = os.path.dirname(self.getselector()) context.addGlobal('dir', TALLoader(self.vfs, dirname)) context.addGlobal('rdir', RecursiveTALLoader(self.vfs, dirname)) template = simpleTAL.compileHTMLTemplate(rfile) rfile.close() template.expand(context, wfile)
def write(self, wfile): rfile = self.vfs.open(self.getselector()) context = simpleTALES.Context(allowPythonPath=self.allowpythonpath) context.addGlobal("selector", self.getselector()) context.addGlobal('handler', self) context.addGlobal('entry', self.getentry()) context.addGlobal('talbasename', self.talbasename) context.addGlobal('allowpythonpath', self.allowpythonpath) context.addGlobal('protocol', self.protocol) context.addGlobal('root', TALLoader(self.vfs, '/')) context.addGlobal('rroot', RecursiveTALLoader(self.vfs, '/')) dirname = os.path.dirname(self.getselector()) context.addGlobal('dir', TALLoader(self.vfs, dirname)) context.addGlobal('rdir', RecursiveTALLoader(self.vfs, dirname)) template = simpleTAL.compileHTMLTemplate(rfile) rfile.close() template.expand(context, wfile)
def write(self, wfile): context = simpleTALES.Context(allowPythonPath=self.allowpythonpath) context.addGlobal("selector", self.getselector()) context.addGlobal("handler", self) context.addGlobal("entry", self.getentry()) context.addGlobal("talbasename", self.talbasename) context.addGlobal("allowpythonpath", self.allowpythonpath) context.addGlobal("protocol", self.protocol) context.addGlobal("root", TALLoader(self.vfs, "/")) context.addGlobal("rroot", RecursiveTALLoader(self.vfs, "/")) dirname = os.path.dirname(self.getselector()) context.addGlobal("dir", TALLoader(self.vfs, dirname)) context.addGlobal("rdir", RecursiveTALLoader(self.vfs, dirname)) # SimpleTAL doesn't support reading from binary files with self.vfs.open(self.getselector(), "r", errors="replace") as rfile: template = simpleTAL.compileHTMLTemplate(rfile) template.expand(context, wfile)
def _runTest_(self, txt, result, errMsg="Error", allowPythonPath=0): self.context = simpleTALES.Context(allowPythonPath=allowPythonPath) self.context.addGlobal('top', 'Hello from the top') self.context.addGlobal('exceptFunc', exceptionalFunction) self.context.addGlobal('helloFunc', simpleFunction) self.context.addGlobal( 'helloPath', simpleTALES.PathFunctionVariable(simpleFunction)) self.context.addGlobal('helloFunction', helloFunction) self.context.addGlobal('myList', [1, 2, 3, 4, 5, 6]) self.context.addGlobal('testing', 'testing') self.context.addGlobal('map', {'test': 'maptest'}) self.context.addGlobal('data', {'one': 1, 'zero': 0}) template = simpleTAL.compileHTMLTemplate(txt) file = io.StringIO() template.expand(self.context, file) realResult = file.getvalue() self.failUnless( realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template))
def _runTest_(self, txt, result, errMsg="Error", allowPythonPath=0): self.context = simpleTALES.Context(allowPythonPath=allowPythonPath) self.context.addGlobal('top', 'Hello from the top') self.context.addGlobal('helloFunc', simpleFunction) self.context.addGlobal( 'helloPath', simpleTALES.PathFunctionVariable(simpleFunction)) self.context.addGlobal('helloFunction', helloFunction) self.context.addGlobal('myList', [1, 2, 3, 4, 5, 6]) self.context.addGlobal('testing', 'testing') self.context.addGlobal('map', {'test': 'maptest'}) self.context.addGlobal('data', {'one': 1, 'zero': 0}) testXML = '<?xml version="1.0" encoding="utf-8"?><root><title type="Example">This is a test</title></root>' xmlTree = simpleElementTree.parseFile(io.StringIO(testXML)) self.context.addGlobal("xml", xmlTree) template = simpleTAL.compileHTMLTemplate(txt) file = io.StringIO() template.expand(self.context, file) realResult = file.getvalue() self.failUnless( realResult == result, "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s" % (errMsg, txt, realResult, result, template))