• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python simpleTAL.compileHTMLTemplate函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中simpletal.simpleTAL.compileHTMLTemplate函数的典型用法代码示例。如果您正苦于以下问题:Python compileHTMLTemplate函数的具体用法?Python compileHTMLTemplate怎么用?Python compileHTMLTemplate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了compileHTMLTemplate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: simpletal

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
开发者ID:anandology,项目名称:notebook,代码行数:25,代码来源:basic.py


示例2: prepare

 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()))
开发者ID:perryhau,项目名称:Mole,代码行数:8,代码来源:template.py


示例3: writeScheme

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()
开发者ID:MrFelixU,项目名称:oink,代码行数:58,代码来源:buildschemes.py


示例4: prepare

 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()))
开发者ID:achimnol,项目名称:dotfiles,代码行数:9,代码来源:bottle_template.py


示例5: _runTest_

	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))
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:10,代码来源:DefineSlotsTests.py


示例6: _runTest2_

	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))
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:7,代码来源:DefineMacroTests.py


示例7: _runCompileTest_

	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)				
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:7,代码来源:DefineSlotsTests.py


示例8: _runTest_

	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))
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:7,代码来源:NoCallTests.py


示例9: apply_to

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()
开发者ID:oaubert,项目名称:advene2,代码行数:34,代码来源:tal.py


示例10: testUTF8ToISO

	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)
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:7,代码来源:TALEncodingTestCases.py


示例11: testCompileTemplateText

	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))
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:33,代码来源:TypesTestCases.py


示例12: testMacroExpansionSlots

	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.')
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:7,代码来源:MacroExpansionTestCases.py


示例13: testCompileTemplateBinary

	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))
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:25,代码来源:TypesTestCases.py


示例14: _runCacheTest_

	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))
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:7,代码来源:PathTests.py


示例15: testContentStructure

	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')    
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:8,代码来源:TALReplaceTestCases.py


示例16: testUnicodeSubclass

	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)
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:9,代码来源:TALEncodingTestCases.py


示例17: testUnbalancedCloseTag

	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
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:9,代码来源:TALHandlerTestCases.py


示例18: testISOToUTF8

	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)
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:10,代码来源:TALEncodingTestCases.py


示例19: do_error

	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()
开发者ID:ph1l,项目名称:halo_radio,代码行数:10,代码来源:TopWeb.py


示例20: testContentStructure

	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')   
开发者ID:janbrohl,项目名称:SimpleTAL,代码行数:10,代码来源:TALContentTestCases.py



注:本文中的simpletal.simpleTAL.compileHTMLTemplate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python simpletemplate.SimpleTemplate类代码示例发布时间:2022-05-27
下一篇:
Python simplestyle.parseStyle函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap