0

Below is an example of how I am using d3.js with web2py controller. This is working for me.

But, I would prefer to use d3.js within an existing bootstrap page using web2py's default bootstrap layout. When I put this d3.js code into the bootstrap layout it does not cause any errors, but I am not seeing an <svg> tag appended to <body>.

Can someone post an example of how this can be done?

controllers/d3js.py:

import random 
def histogram():
    dataset = [(random.randint(1,6) + random.randint(1,6)) for i in range(100)]
    return dict(dataset=dataset, title='D3.js Histogram')

view/d3js/histogram.html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>{{=title}}</title>
        <script type="text/javascript" src="https://d3js.org/d3.v3.min.js" ></script>
    </head>
    <body>
        <script type="text/javascript">

            {{from gluon.serializers import json}}
            var dataset = {{=XML(json(dataset))}};

            //Width and height
            var w = 600;
            var h = 600;
            ...

            //Create SVG element
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);

            ...

        </script>
    </body>
</html>

The source of this d3.js sample is Scott Murray's book, Interactive Data Visualizations for the Web.

ChrisGuest
  • 3,398
  • 4
  • 32
  • 53
  • The above code works? *When I put this d3.js code into the bootstrap layout*, what does that code look like? – Mark Dec 17 '15 at 16:27

1 Answers1

0

In /views/default/histogram.html, if you have:

{{extend 'layout.html'}}
[Your D3 HTML code]

this will cause a problem because everything after the {{extend}} statement gets inserted where the {{include}} appears in layout.html, which is within the <body> tag (so, you are including a new <html> tag and <body> tag within the existing <body> tag).

Instead, in your histogram.html view, include only the parts of the HTML that are inside the <body> tag. In that case, you will also need to make sure the D3 library gets loaded, so you could either move that <script> tag inside the body, or you could add it via web2py's response.files:

response.files.append('https://d3js.org/d3.v3.min.js')
Anthony
  • 25,466
  • 3
  • 28
  • 57