Pass the variable in IPython / Jupyter to the html block (%% html)

I would like to pass a simple variable to an html cell on a Jupyter:

cell 1:

a=5

cell 2:

%%html
<html>
  <head>
    <script type="text/javascript">
    window.alert(a);
    </script>
  </head>
</html>

This will return an error:

Javascript error adding output!
ReferenceError: a is not defined
See your browser Javascript console for more details.
+4
source share
1 answer

This is a hacker solution:

a=5

html_code ="""
<html>
  <head>
    <script type="text/javascript">
    window.alert(%s);
    </script>
  </head>
</html>""" % a

from IPython.display import HTML
HTML(html_code)
+2
source

All Articles