I have an csv file, the data, and an HTML file, the template.
I want a script that will create an individual html file per record from the csv file, using the html file as a template.
Which is the best way to do this in Ruby? Python? Is there a tool/library I can use for this in either language?
Python with Jinja2.
import jinja
import csv
env= jinja.Environment()
env.loader= jinja.FileSystemLoader("some/directory")
template= env.get_template( "name" )
rdr= csv.reader( open("some.csv", "r" ) )
csv_data = [ row for row in rdr ]
print template.render( data=csv_data )
It turns out that you might be able to get away with simply passing the rdr
directly to Jinja for rending.
If the template looks like this, it will work with a wide variety of Python structures, including an iterator.
<table>
{% for row in data %}
<tr>
<td>{{ row.0 }}</td><td>{{ row.1 }}</td>
</tr>
{% endfor %}
</table>
Ruby has built in CSV handling which should make it fairly trivial to output static HTML files.
See:
Actually, so does Python, so it's really a matter of personal preference (or of whichever you already have configured).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With