将JS变量替换为一个Jinja模板的字符串

问题描述

我的客户端事件处理程序如下:

socket.on('received_message',function(data){
           console.log(data);

           var actual="{% if "+int(data['user_id'])+"==current_user.id %}<div class=\"user\" id=\"postof"+data['post_id']+"\"\"><span><strong><u>"+data['username']+"</u></strong></span><a href=\"{{url_for('delete_post',post_id="+data['post_id']+",thread_id="+data['thread_id']+")}}\">Delete</a><p>"+data['msg']+"</p></div>{% else %}<div class=\"notuser\" id=\"postof"+data['post_id']+"\"><span><strong><u>"+data['username']+"</u></strong></span><p>"+data['msg']+"</p></div>{% endif %}";
           console.log("{{dif_user}}")
           console.log('{{current_user.id}}'+"  "+data['user_id']);
           console.log(actual);
           document.getElementById('posts').innerHTML+=actual;
           $('.container').scrollTop($('.container')[0].scrollHeight);
         });

我对上述事件处理程序的服务器端调用

socketio.emit('received_message',{'room':data['room'],'user_id':p.user_id,'username':user_.username,'msg':p.message,'post_id':p.id,'thread_id':thread_.id},room=data['room'],dif_user=p.user_id)

现在,该代码无法正常工作,因为插入的jinja代码始终会导致其他部分的执行。如何将js变量data['user_id']合并到我创建的actual变量中,以便flask正确呈现它。

我认为flask正在将替换的data['user_id']作为字符串,从而使else部分得以执行。

解决方法

您必须考虑到Jinja模板是在通过render_template返回模板时执行的,因此,将使用当时的变量值来决定使用if块或else块。客户端接收到Socket.IO事件时,不会重新评估该条件,因为该事件将在客户端中接收而无需Python的干预。

如果希望客户端在接收到Socket.IO事件时评估条件,则必须使用JavaScript编写条件。