Template for CGI
Marco Musazzi
marco.musazzi at sofositalia.it
Fri Nov 5 15:48:57 EST 1999
>On Tue, 2 Nov 1999, Glenn Kidd wrote:
>> I am a newbie to Python and I have a question. I want a CGI script that
>> will read a file template and replace certain words with variables. Ii
>> tried putting the variable names in the file but it is read as palin
text.
>> Is there a way to embed variables into a teplate or a replace function in
>> Python? Thank you for any help you give.
You can use something like this:
template file:
your template text your template text %variable% your template text
%variable2%
%xxx% is the placeholder for "variable" xxx (you can replace % with what you
like)
in your python code:
import string
template = open("yourtemplatefile")
templateText = template.read()
template.close()
templateText = string.replace(templateText, "%variable%",
str(value_of_variable))
templateText = string.replace(templateText, "%variable2%",
str(value_of_variable2))
# an so on....
# printing a minimal http header
print "Content-type: text/html"
print
# printing the template filled with the variables
print templateText
You can do it better using a value-filled dictionary:
val = {"variable":value1, "variable2":value2, etc...... } # you may read
this dict from a shelv db for example...
for k in val.keys():
templateText = string.replace(templateText, "%"+ k + "%", val[k] )
# printing a minimal http header
print "Content-type: text/html"
print
# printing the template filled with the variables
print templateText
And you can use both the mothods at the same time...
happy coding
Marco
More information about the Python-list
mailing list