This is just a quick note on something that I had a hard time finding how to do online which I thought might be useful to others.

I’m working on a Flask web-server using Jinja templates to visualize some d3 drawings.

I want to display multiple d3 plots in the same Jinja template.

Furthermore, the data for each of the plots has to be passed by flask.

To simplify the setting, let’s say that flask has a list of colors with which we want to draw one circle for each color in d3.

Turns out you can use Jinja to format JavaScript calls.

So if you want to have multiple d3 plots which depend on some data from the server, you can use a Jinja for loop with repeated calls to d3.

All you have to do is package your d3 drawing code in a function which can take arguments from Flask (via Jina).

See full code below:

In /app.py


from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def home():
    stuff = ['red', 'blue', 'green', 'orange']
    return render_template('home.html', things=stuff)

if __name__ == "__main__":
    pass

In templates/home.html

<script src="https://d3js.org/d3.v4.min.js"></script> 
<body>
</body>


{% for thing in things %}

	<script>
		draw("{{ thing }}");

		function draw(x){
			var svg = d3.select("body")
				    .append("svg")
				    .append("g")
			    svg.append("circle")
			       .attr("cx", 30)
			       .attr("cy", 30)
			       .attr("r", 20)
			       .attr("fill", x)
		}

	</script>

{%endfor %}


Here’s what that looks like on my end: