1

I'm trying to pass a string of generated HTML from Python to Javascript. This is the simplified version of my view (using Pyramid framework).

@view_config(route_name='view_page', renderer='templates/page.jinja2', permission='view')
def view_cosmeceutical(request):
    gen_html = markdown( ingredient.desc )
    return dict(gen_html=gen_html)

From this thread, I saw that I can use {{ variable }} in Javascript too, so in my JS file, I have a function that attempts to change the innerHTML of the element with the id 'content-desc'. But all I'm getting is the string {{ genHTML }} instead of the actual variable containing the generated HTML.

function insertHTML() {
    genHTML = '{{gen_html}}';
    $('#content-desc').html(genHTML);
}

What am I doing wrong?

Community
  • 1
  • 1
bard
  • 2,762
  • 9
  • 35
  • 49

1 Answers1

2

One good way to pass data and content from the server-side Python to JavaScript are

  • JSON embeds in HTML

  • Separate AJAX calls which serve JSON objects as application/json mime

For the embed approach, I would do somethibng along the lines to export data to the page template as JSON:

   import json

   gen_html = ...
   javascript_data = json.dumps(dict(gen_html=gen_html))
   return dict(javascript_data=javascript_data)

Then in the page template pass this to JavaScript global variables:

   <script>
          window.javascriptData = {{javascript_data}}; // Check need to escape HTML in your case
   </script>   

And then in JavaScript (keep preferably in a separate static .JS file):

   $(document).ready(function() {
         $('#content-desc').html(window.javascriptData.gen_html);
   });

Also, I would not generate HTML for just passing it to JavaScript in the first place. Instead, I would pass raw data to JavaScript as JSON, and then generate HTML on the client-side from this data using client-side templating. This increases the complexity, but is more "clean" and flexible.

Example microtemplating engines for the client-side JavaScript:

DOM tree based JavaScript template engines

Community
  • 1
  • 1
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • I'm generating HTML from Markdown on the server side using Python Markdown, so I'm not sure how to do that on the client-side instead (haven't found a good enough Markdown parser in JS). Following your code, ``window.javascriptData;`` gives an associative array ``{"desc_html": "

    Test

    This is the desc

    "}`` , but ``window.javascriptData.gen_html;`` is ``undefined``.
    – bard Feb 19 '14 at 13:46
  • It seems to be because ``window.javascriptData`` is actually a string, not an object... – bard Feb 19 '14 at 13:54
  • Use View Source to find out what goes to your HTML file. – Mikko Ohtamaa Feb 19 '14 at 13:57