我正在尝试从CSV文件创建的python dict渲染jinja2模板,但是jinja2对dict采取了异常,我不明白为什么。
这是模板:
{% for key, value in hostname.iteritems() %} interface {{ key }} description {{ value }} {% endfor %}这是python代码:
import csv from pprint import pprint import os import jinja2 CSVDATA_FILENAME = 'port_descriptions.csv' TEMPLATE_FILENAME = 'cisco.j2' hostnames = [] env = jinja2.Environment( loader=jinja2.FileSystemLoader(os.getcwd()), trim_blocks=True, lstrip_blocks=True) template = env.get_template(TEMPLATE_FILENAME) for row in csv.DictReader(open(CSVDATA_FILENAME)): if row['hostname'] not in hostnames: hostnames.append(row['hostname']) for hostname in hostnames: x = hostname hostname = {} for row in csv.DictReader(open(CSVDATA_FILENAME)): if x == row['hostname']: hostname[row['port']] = row['des'] pprint(hostname) print template.render(hostname)在倒数第二行(pprint(hostname)) ,代码将根据需要打印主机名字典,所以我知道它们在那里,但jinja2不会渲染它们。 我在这里错过了一些明显的东西,在模板中可能吗? 据我所知,我的代码遵循这一点 - http://keepingitclassless.net/2014/03/network-config-templates-jinja2/非常接近,但我必须忽视一些事情?
I'm trying to render a jinja2 template from a python dict created from a CSV file, but jinja2 is taking exception to the dict and I don't understand why.
This is the template:
{% for key, value in hostname.iteritems() %} interface {{ key }} description {{ value }} {% endfor %}and this is the python code:
import csv from pprint import pprint import os import jinja2 CSVDATA_FILENAME = 'port_descriptions.csv' TEMPLATE_FILENAME = 'cisco.j2' hostnames = [] env = jinja2.Environment( loader=jinja2.FileSystemLoader(os.getcwd()), trim_blocks=True, lstrip_blocks=True) template = env.get_template(TEMPLATE_FILENAME) for row in csv.DictReader(open(CSVDATA_FILENAME)): if row['hostname'] not in hostnames: hostnames.append(row['hostname']) for hostname in hostnames: x = hostname hostname = {} for row in csv.DictReader(open(CSVDATA_FILENAME)): if x == row['hostname']: hostname[row['port']] = row['des'] pprint(hostname) print template.render(hostname)At the penultimate line (pprint(hostname)) the code will print the hostname dictionaries as desired so I know they are there, but jinja2 won't render them. Am I missing something obvious here, in the template maybe? As far as I can see my code follows this - http://keepingitclassless.net/2014/03/network-config-templates-jinja2/ pretty closely, but I must be overlooking something?
最满意答案
在文档中查看此示例 ,您可能需要将字典作为命名关键字参数传递,如下所示: print template.render(hostname=hostname)
请注意,只有等号左边的部分与模板相关; 你可以做template.render(hostname={'testy': 'testy'}) ,同样的模板会继续工作。
Looking at this example in the docs, you probably need to pass your dictionary as a named keyword argument, like this: print template.render(hostname=hostname)
Note that only the part on the left of the equals sign is relevant to the template; you could just do template.render(hostname={'testy': 'testy'}) and the same template would keep working.
更多推荐
发布评论