JSON is appearing as unicode entities in Jinja2 template

前端 未结 3 1211
傲寒
傲寒 2021-01-04 06:20

I using Jinja2 with webapp2.

Jinja2 encodes all \'context\' data into unicode as their doc says. This is proving problematic when I try to insert a json string into

3条回答
  •  爱一瞬间的悲伤
    2021-01-04 07:18

    If you don't need to act on the array in the Jinja side, but just need to pass the packet to javascript, I would recommend using:

    json.dumps(python_object_or_array)
    

    https://docs.python.org/2/library/json.html

    This stringified variable, when passed into jinja gets passed down to javascript without getting the pythonic unicode markings on variables. And incidentally, will likely fix True and False getting fixed to true and false as javascript would expect.

    So in the context of flask, it would look something like this:

    @app.route('/')
    def home():
         if userNeedsToLogin():
              session['routePath'] = request.full_path
              return render_template('login.html', error=None)
         else:
              return render_home()
    
    def render_home():
         print "Rendering Home"
         results = get_some_database_query_results()
         data_out = json.dumps(results)
         return render_template('home.html', data=data_out)
    

    home.html

    
    
    
      
    
    
      
      
    
    
    

提交回复
热议问题