Search code examples
javascriptflaskjinja2quart

How to use javascript data in Quart/Flask/Jinja2 template tag?


I am using websockets within my Quart app in place of ajax. The aim is to be able to post a comment. A Quart websocket endpoint handles the backend side of things, and then I would like to append the comment to the page instantly from the data received from the websocket. This all working fine until I want to use either a template filter or utility context processor. I think some code will people to understand, so here is my websocket method in JavaScript/jQuery:

  $(function() {
    $('.comment_form').submit(function (e) {
      var add_comment_ws = $.simpleWebSocket({
        url: 'wss://' + document.domain + ':' + location.port + '/websockets/_add_comment',
        timeout: 100,
        attempts: 10,
        dataType: 'json'
      });
      if (typeof $(this).data('post_id') !== 'undefined') {
        var post_id = $(this).data('post_id');
      } else {
        var post_id = null;
      }
      if (typeof $(this).data('reply_id') !== 'undefined') {
        var reply_id = $(this).data('reply_id');
      } else {
        var reply_id = null;
      }
      var data = {
        comment_body: $(this).find('textarea').val(),
        post_id: post_id,
        reply_id: reply_id,
        user_id: $(this).data('user_id'),
        complete: false
      };
      console.log('[+] Sending data to websocket: <add_comment_ws>: content: ' +
        $.each(data, function(key, value) {
          console.log(key + ' - ' + value);
        })
      );
      add_comment_ws.send(data);
      $(this).find('textarea').val('')

      add_comment_ws.listen(function(data) {
        console.log('[+] Received data from websocket: <add_comment_ws>: content: ' +
          $.each(data, function(key, value) {
            console.log(key + ' - ' + value);
          })
        );
        var comments_list = $('#comments_list_for_' + data.id);
        var comment_html = '<div class="comment">' +
                            '<p>' + data.comment_body +
                            '<p>' + data.user_display_name +
                            '<hr>' +
                            '</div>';
                            '<div class="comment">' +
                            ' <hr>' +
                            '  <div class="comment-grid-conatiner">' +
                            '    <div class="comment-grid-item-1">' +
                            '      <div class="comment-option-buttons comment-option-buttons-grid-conatiner">' +
                            '        <button class="comment-vote-up-button vote-button pseudo comment-option-buttons-grid-item-1" title="This comment is useful." aria-label="up vote" data-comment_id="' + data.comment_id + '" data-user_id="' + data.user_id + '"><i class="fal fa-thumbs-up"></i></button>' +

                            '        <div class="vote-count comment-option-buttons-grid-item-2 comment-vote-count-' + data.comment_id + '" itemprop="upvoteCount" data-value="' + data.comment_score + '">' + data.comment_score + '</div>' +

                            '        <button class="vote-button pseudo comment-option-buttons-grid-item-3" title="This comment needs to be flagged." aria-label="up vote"><i class="fal fa-flag"></i></button>' +
                            '      </div>' +
                            '    </div>' +
                            '    <div class="comment-grid-item-2">' +
                            '      <p class="comment-body">' + data.comment_body + '</p>' +
                            '    </div>' +
                            '    <div class="comment-grid-item-3">' +
                            '      <span class="comment-display-name comment-grid-item-2">' +
                            '        <a class="comment-display-name-link" href="/users/user/' + data.user_id + '">' +
                                      data.user_display_name +
                            '        </a>' +
                            '      </span>' +
                            '      <span class="comment-date">' +
//This is where the problem is  --->> {{ human_date(data.created_at) }} + //<<--- 
                            '      </span>' +
                            '    </div>' +
                            '  </div>' +
                            '  <hr>';
        comments_list.append(comment_html);

      });
      e.preventDefault();
    });

I have marked where the problem is in the code (it's at close to the bottom).

I receive an exception:

jinja2.exceptions.UndefinedError: 'data' is undefined

Which is expected at this point because within the jinja tag itthinks we are using python variables.

Is there a way to be able to do this?


Solution

  • Ok so I rectified this by using Chris G's suggestion in the comments. I ended up moving the HTML into a template and using the websocket endpoint to render the data in the HTML and return the HTML as the to the JavaScript.