You are not logged in.
Hi.
When I code PHP I like to use this template system. A short instance would consist of 2 files: "index.php" and "template.php".
template.php:
<?php
echo "<h1>$header</h1>";
echo "<p>$text</p>";
?>
index.php:
<?php
$header = "this is a header";
$text = "this is a text";
include "template.php";
?>
So I can use one template for lots of pages - same layout but different vars.
I cannot find how to do this in Python CGI.
page.cgi:
#!/usr/bin/python
import os, cgi
x = "This is the page text."
eval(open('template.cgi').read())
template.cgi
print("Content-type: text/html\n")
print(x)
This gives me error 500. I am not surprised, this mail.python.org page says:
> I can't figure out how one would approach this in Python (i'm using
> mod_python). There's no equivalent to the "include" function from
> PHP.Correct, the concept doesn't exist because you are working
with vanilla CGI rather than server scripting.
But maybe there is a way to make something similar?
Last edited by Mr. Alex (2012-06-05 17:52:42)
Offline
Well, first a meta question: Do you need it to be vanilla CGI + python? There are (micro)frameworks like bottle that do templates and webstuff for you more easily.
฿ 18PRsqbZCrwPUrVnJe1BZvza7bwSDbpxZz
Offline
Yes, I prefer vanilla CGI. I just don't get those frameworks.
Offline
Template (index.html.tpl)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Main Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
h1 {{
margin: auto;
}}
</style>
</head>
<body>
<h1>Admin</h1>
<ul>
<li><a href="{}">Monthly Report</a></li>
<li><a href="{}">Inventory Zip Files</a></li>
<li><a href="{}">Order Reports</a> -- Last 7 days</li>
<li><a href="{}">Notes/TODO/Information</a></li>
<li><a href="{}">EDI Orders</a></li>
</ul>
</body>
</html>
index.py :
#!/usr/bin/env python2
def main():
template = "index.html.tpl"
pages = ("monthly", "zips", "reports", "vimwiki", "edi.py")
sitename = "/"
pages = ["{}{}".format(sitename, pages) for i in pages]
tpl = "".join(open(template,'r').readlines())
print 'Content-type: text/html\n\n' + tpl.format(*pages)
if __name__ == '__main__':
main()
Maybe not the best way...but it works for me Notice the double {{ }} in the template where you want literal brackets, not placeholders.
Scott
Offline
Wow, that was not obvious. Thanks.
Offline
Instead of using indexed variables, you can use a dictionary:
...
<span>Hello, my name is {name}.</span>
...
...
environment = {"name": "The Name"}
print 'Content-type: text/html\n\n' + tpl.format(**environment)
Offline
@Steblien: thanks! Good idea.
@Mr. Alex: nope, not obvious except in hindsight...it took awhile for me to figure out too! Don't forget to mark your post [Solved]
Scott
Offline