Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top