2

I'm trying to build out a configuration file using jinja2. I have a bunch of data in a csv that I want to use for the jinja2 template.

I can open and read the csv file but just not sure how to get jinja2 to read the data from the CSV and add it into the variables of the template. This is the start of my config:

import jinja2
import csv

with open('dhcpd.csv', 'rb') as csvfile:
    build = csv.reader(csvfile)

env =   jinja2.Environment(loader=jinja2.FileSystemLoader('/templates'))
template = env.get_template('dhcpd-build')

I know i'm a fair way off, but any help would be great

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
McJim
  • 39
  • 1
  • 5

2 Answers2

1

The process here is

Example:

data = list(data)
result = template.render(data=data)

Then you can iterate data in the template:

{% for row in data %}
    {{ row }}
{% endfor %}

Code not tested in the real life, I wrote out of my head.

Community
  • 1
  • 1
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • Thanks for the input, i've got a little closer now, but the variables from my csv file are not making it into the template. – McJim Aug 04 '15 at 13:27
  • 1
    Please edit the question and add output, your template and possible error messages. Do not add answers, you should be able to edit the questions. – Mikko Ohtamaa Aug 05 '15 at 15:33
0

Code now looks like

import jinja2
import csv

with open('dhcpd.csv', 'rb') as infile:
  reader = csv.reader(infile)
  build = list(reader)


env = jinja2.Environment(loader=jinja2.FileSystemLoader('/Users/Luca/Git/ztp/templates'))
template = env.get_template('dhcpd-build')
for data in build:
  print template.render(data=build)

It renders the template but does not have any of the variables from my csv file

McJim
  • 39
  • 1
  • 5