简体   繁体   English

Jinja2模板渲染获取空字符串

[英]Jinja2 template rendering getting empty string

I am getting a response from the REST service. 我收到REST服务的回应。 This response is an array of JSON objects. 此响应是JSON对象的数组。 Using this array, I am trying to display the individual property of each JSON object on HTML page using Jinja2 template framework. 使用这个数组,我试图使用Jinja2模板框架在HTML页面上显示每个JSON对象的单独属性。 But it is showing the empty string on the browser. 但是它在浏览器上显示空字符串。

The JSON response which I am getting from the service is 我从服务中获得的JSON响应是

{
    u'messages': 
    [
        {u'text': u'hello', u'author_id': 1, u'pub_date': 1518506778, u'message_id': 1}, 
        {u'text': u'hell', u'author_id': 2, u'pub_date': 1518420378, u'message_id': 2}, 
    ]
}

Not sure what is the u character before every string. 不确定每个字符串前面的u字符是什么。 The rest service is developed in Flask. 其余服务在Flask中开发。

Below is the python code: 以下是python代码:

r = requests.get('http://127.0.0.1:3000/api/v1.0/messages')
@app.route('/messages')
def public_timeline():
    """Displays the latest messages of all users."""
    python_message = json.loads(r.text)
    print("******")
    print(python_message)
    return render_template('messages.html', messages = python_message)

And the template code is : 模板代码是:

    {% if messages %}

   <ul id=”messages”>
      {% for message in messages %}
         <li>
            <div class=”text”>
               <a>{{message['text']}}</a>
            </div>
         </li>
      {% endfor %}
   </ul>
{% else %}
   <p>Messages not available :(</p>
{% endif %}

I think the problem is due to the unnecessary u character before each string. 我认为问题是由于每个字符串之前不必要的u字符引起的。 How can I resolve problem of blank output on the browser screen? 如何解决浏览器屏幕上空白输出的问题?

The output in the browser is: 浏览器中的输出为:

<html><head></head><body><ul id="”messages”">

     <li>
        <div class="”text”">
           <a></a>
        </div>
     </li> ....  

You have Unicode strings, the u prefix is a type indicator. 您有Unicode字符串, u前缀是类型指示符。 They have nothing to do with your issues, and are entirely normal when decoding JSON. 它们与您的问题无关,并且在解码JSON时完全正常。

Your issue is that you are looping over the keys of the outer dictionary , not over the messages contained in the python_message[u'messages'] list. 您的问题是您要遍历外部字典 ,而不是python_message[u'messages']列表中包含的消息。

Get that list; 得到那个清单; using dict.get() you can produce a default value if the key is missing, here a list would be helpful: 如果缺少键,可以使用dict.get()产生一个默认值,这里的列表会有所帮助:

return render_template('messages.html', messages = python_message.get(u'messages', []))

You need to be careful with what editor you are using to write your template, as you have used characters as where you should have used " characters. In your output, it is clear your browser has put correct quotes around those attributes, so now your you have a div with id ”messages” , not messages . 您需要注意使用哪种编辑器来编写模板,因为您使用的是字符,而本应使用的是"字符。在输出中,很明显浏览器在这些属性周围加上了正确的引号,因此现在您有一个ID为”messages”的div,而不是messages

Demo, with corrected quotes: 演示,带有更正的引号:

>>> from jinja2 import Template
>>> python_message = {
...     u'messages':
...     [
...         {u'text': u'hello', u'author_id': 1, u'pub_date': 1518506778, u'message_id': 1},
...         {u'text': u'hell', u'author_id': 2, u'pub_date': 1518420378, u'message_id': 2},
...     ]
... }
>>> template = Template('''
... {% if messages %}
... <ul id="messages">
...    {% for message in messages %}
...       <li>
...          <div class="text">
...             <a>{{message['text']}}</a>
...          </div>
...       </li>
...    {% endfor %}
... {% else %}
...    <p>Messages not available :(</p>
... {% endif %}
... ''')
>>> print(template.render(messages=python_message['messages']))


<ul id="messages">

      <li>
         <div class="text">
            <a>hello</a>
         </div>
      </li>

      <li>
         <div class="text">
            <a>hell</a>
         </div>
      </li>


>>> print(template.render(messages=[]))


   <p>Messages not available :(</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM