pythonhtmlbokehdominate

insert bokeh plot into dominate script


I was wondering if there is any easy way of embedding a Bokeh plot within a dominate template.

I am aiming for something like this:

import dominate
from dominate.tags import *
from bokeh.plotting import figure
from bokeh.embed import components
from bokeh.io import output_file, save

# Create a simple Bokeh figure

output_file(filename="test_plot.html", title="Static HTML file")
plot = figure()
plot.circle([1,2], [3,4])
save(plot)

plot_script, plot_div= components(plot)

doc = dominate.document(title='Report')
doc.add(body()).add(div(id='content'))

with doc.body:
    with table(cls='main_table'):
        with tr():
            td().add(raw(plot_div))

doc.head.add(raw(plot_script))

with open('test.html', 'w') as f:
    f.write(doc.render())

When I open the test.html file with my browser, I cannot see the plot, yet when I open the test_plot.html file, I can clearly see the plot is there. Thus, I was wondering if there is something wrong with this approach or if it is just impossible.


Solution

  • Okay, I think I found the answer to my question. Basically, it is necessary to add the CDN resources to the HTML file. It is possible to do that as:

    doc.head.add(raw('''
        <script src="https://cdn.bokeh.org/bokeh/release/bokeh-x.y.z.min.js" crossorigin="anonymous"></script>
        <script src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-x.y.z.min.js" crossorigin="anonymous"></script>
        <script src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-x.y.z.min.js" crossorigin="anonymous"></script>
        <script src="https://cdn.bokeh.org/bokeh/release/bokeh-gl-x.y.z.min.js" crossorigin="anonymous"></script>
        <script src="https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-x.y.z.min.js" crossorigin="anonymous"></script>
        <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.js"></script>
        <script type="text/javascript">
            Bokeh.set_log_level("info");
        </script>
    '''))