Skip to content

Instantly share code, notes, and snippets.

@xgrg
Last active January 2, 2016 17:08
Show Gist options
  • Save xgrg/8334473 to your computer and use it in GitHub Desktop.
Save xgrg/8334473 to your computer and use it in GitHub Desktop.
Formatting contents from a Python dictionary using a HTML template
<html>
<body>
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
<h1>Some general information about CATI factory</h1>
[<a href="#" onclick="toggle_visibility('foo');">+</a>] disk usage reports
<div id="foo">
<a href="$DATADIR/global_usage.png">global usage</a>
<a href="$DATADIR/studies_usage.png">studies usage</a> <br/>
<a href="$DATADIR/users_usage.png">users usage</a> <br/>
$GENERALINFO
</div>
and there are so far $NUMBER_OF_SUBJECTS subjects in the database !
<br/>
[<a href="#" onclick="toggle_visibility('foo');">+</a>]
<div id='foo' style="display:none">
$DETAILED_DIRECTORIES
</div>
</body>
</html>
def generate_from_template(template_pathname, conversion_hashtable):
'''
This command takes an HTML template file, converts its tags (starting with a
dollar character) using a hashtable ``conversion_hashtable`` provided as
argument, and returns the converted string.
'''
import string
html_report = ''
template_file = open(template_pathname, 'rb')
for line in template_file:
for tag in conversion_hashtable.keys():
if string.find(line, tag) != -1:
#value = conversion_hashtable.pop(tag) #uncomment if tag supposed to be unique in the template
value = conversion_hashtable[tag]
line = line.replace(tag, str(value))
html_report += line + '\n'
return html_report
conversion_hashtable = {'$GENERALINFO': 'coucou',
'$DETAILED_DIRECTORIES' : 'detailed info on directories',
'$DATADIR' : './path_to_images',
'$NUMBER_OF_SUBJECTS': '1000'}
generate_from_template('/home/go231605/index.html', conversion_hashtable)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment