简体   繁体   English

使用html模板格式化csv文件数据

[英]Formatting csv file data with html template

I have an csv file, the data , and an HTML file, the template . 我有一个csv文件, 数据和一个HTML文件, 模板

I want a script that will create an individual html file per record from the csv file, using the html file as a template. 我想要一个脚本,它将使用html文件作为模板,从csv文件为每条记录创建一个单独的html文件。

Which is the best way to do this in Ruby? 在Ruby中这是最好的方法吗? Python? 蟒蛇? Is there a tool/library I can use for this in either language? 我用这两种语言都可以使用这个工具/库吗?

Python with Jinja2 . Python与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. 事实证明,你可以通过简单地将rdr直接传递给Jinja进行撕裂来逃脱。

If the template looks like this, it will work with a wide variety of Python structures, including an iterator. 如果模板看起来像这样,它将适用于各种Python结构,包括迭代器。

<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. Ruby内置了CSV处理功能,这使得输出静态HTML文件变得非常简单。
See: 看到:

Actually, so does Python, so it's really a matter of personal preference (or of whichever you already have configured). 实际上,Python也是如此,所以它实际上是个人偏好的问题(或者你已经配置的那个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM