3

When I put my d3 code directly into my base.html, it runs with no issues, however when I place it into an extending template, nothing shows up except the static text from the template. I'm not importing any data. I've tried moving my script tags from base.html to index.html, but that hasn't had an effect.

base.html:

<html>
  <head> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> 
  </head>
  <body>
  {% block content %}{% endblock %}
  </body>
</html>

index.html:

{% extends "base.html" %} {% block content %}
<h1>hks;dhf;</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
  var circles = [30, 70, 110];

  var container = d3.select("div").append("svg")
    .attr("width", 200)
    .attr("height", 200);

  var circles = container.selectAll("circle")
    .data(circles)
    .enter()
    .append("circle");
  console.log("here it is")

  var circleAttributes = circles
    .attr("cx", function(d) {
      return d;
    })
    .attr("cy", function(d) {
      return d;
    })
    .attr("r", 20)
    .style("fill", function(d) {
      var returnColor;
      if (d === 30) {
        returnColor = "green";
      } else if (d === 70) {
        returnColor = "purple";
      } else if (d === 110) {
        returnColor = "red";
      }
      return returnColor;
      console.log(circles);
    });
</script>

<div>
</div>
{% endblock %}

How do you display d3 with static data on a Flask template extension?

fstopzero
  • 1,073
  • 2
  • 10
  • 24

1 Answers1

0

What is likely happening is that the d3 code is being run before the dom is ready. You can try moving the div above the script tag or even better run your d3 code in a on document ready hook.

Also it's not a bad idea to define a separate jinja block for all scripts

Ciaran Liedeman
  • 779
  • 5
  • 13