faqts : Computers : Programming : Languages : Python : Snippets : Web Programming / Manipulating HTML files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

8 of 9 people (89%) answered Yes
Recently 3 of 4 people (75%) answered Yes

Entry

Mixing HTML and Python

Jul 5th, 2000 10:03
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 357, Rafal Smotrzyk


"""
Packages: text.html
"""
"""
From:           	"Rafal Smotrzyk" <rav@smo3k.z.pl>
Subject:        	Re: An idea - request for comments
Date sent:      	Wed, 04 Aug 2020 14:05:36 GMT
To:             	python-list@cwi.nl
"""
#Simple but working
import re
class Response:
   def __init__(self):
      self.HTMLDocument=''
   def write(self,adata):
      self.HTMLDocument=self.HTMLDocument+adata
def GetTextAsHTMLText(s,repldict={}):
   for akey in repldict.keys():
      c=re.compile('\<\%\= *'+akey+' *\%\>', re.I)
      s=c.sub(repldict[akey],s)
   c=re.compile('\<\%', re.I)
   s=c.sub('""")',s)
   c=re.compile('\%\>', re.I)
   s=c.sub('Response.write("""',s)
   s='Response.write("""'+s+'""")'
   aresponse=Response()
   gdict={'Response':aresponse}
   exec s in gdict,repldict
   return aresponse.HTMLDocument
def DoTest():
   ahtmlsource=r"""
<HTML>
<BODY>
<%
Response.write('<h1>'+ScriptName+'</h1>\n')
Response.write('<table>')
x=0
while x<10:
   s='<tr><td>%s</td><td>%s</td></tr>\n'%('d1_'+`x`,'d2_'+`x`)
   Response.write(s)
   x=x+1
Response.write('</table>')
%>
<p>
<%
for i in range(10):
   Response.write(`i`+',')
Response.write('<br>')
%>
Test line 1 = <%= Test1 %>
Test line 2 = <%=Test2%>
</p>
</BODY></HTML>
"""
   adict={'Test1':'this is page constant','Test2':'another constant',
    'ScriptName':'This is script name'}
   s=GetTextAsHTMLText(ahtmlsource,adict)
   print s
if __name__=='__main__':
   DoTest()
# Rafal Smotrzyk