4

我正在尝试创建一个 HTML 表来显示 mongodb 集合的内容。该集合包含有关来自小型企业的不同客户订单的数据。某些数据将始终存在于给定文档中,例如客户姓名和电话号码。但是,每个文档中的某些数据需要有所不同,例如订购的商品,因为一个客户可能订购 1 件商品,而另一个客户可能订购 3 件商品。那么,如果我有一个 mongodb 集合,其中包含每个文档中包含任意数字字段的文档,我如何动态地将它们添加到 HTML 表中以显示文档的内容?作为我正在寻找的显示类型的示例,这里是我知道将保持不变的字段的硬编码 HTML。

 <!DOCTYPE html>
 <html>
  <head>
    <head>
    <title>Invoice Report</title>
    <style type="text/css">
     body {font-family:sans-serif;color:#4f494f;}
     form input {border-radius: 7.5px;}
     h5 {display: inline;}
     .label {text-align: right}
     .ordersBook {float:left; padding-top: 10px;}
     .name {width:100%;float:left; padding:3px;}
     .wrapper { padding-left: 25px; padding-top: 20px}
    </style>
    <script type="text/javascript">
    var itemRe = /item*/;
    }
    </script>
   </head>
  </head>
  <body>
     <div class="invoice">

      <h4>Order Form:</h4>
<table border="1">
<tr>
  <th>Name:</th>
  <td>{{rows['name']}}</td>
</tr>
<tr>
  <th>Created:</th>
  <td>{{rows['created']}}</td>
</tr>
<tr>
  <th>Phone:</th>
  <td>{{rows['phone']}}</td>
</tr>
<tr>
  <th>Email:</th>
  <td>{{rows['email']}}</td>
</tr>
<tr>
  <th>Item:</th>
  <td>{{rows['item']}}</td>
  </tr>
</div>
  <tr>
    <th>Quantity:</th>
    <td>{{rows['qty']}}</td>
  </tr>
  <tr>
    <th>Color:</th>
    <td>{{rows['color']}}</td>
  </tr>
  <tr>
    <th>Quote:</th>
    <td>{{rows['quote']}}</td>
  </tr>

</table>
     </div>


  </body>
 </html>

动态创建整个表可能会更好,但我不确定在哪里执行此操作的正确位置

  • 在 HTML 文件中的 javascript 函数中?
  • 或者可能在维护 mongodb 数据库中信息的 pymongo 文件中?

处理将 mongodb 文档发送到 HTML 表单的 python 代码使用 python Bottle 模板。

@bottle.route('/view/<_id>', method = 'GET')
def show_invoice(_id):
    client = pymongo.MongoClient("mongodb://localhost")
    db = client.orders
    collection = db.myorders
    from bson.objectid import ObjectId
    result = collection.find_one({'_id': ObjectId(_id)})
    return bottle.template('invoice', rows = result)

我非常感谢有人可以提供的任何帮助!=)

4

1 回答 1

2

Looking over the documentation for the bottle template engine, it looks like you can use 'ifs' and 'fors' to accomplish this.

For instance, if you order is stored at rows['orders'] and you don't know how many there are, in your template you can place:

%for item in rows['orders']:
  <td>{{item}}</td>
%end

or say that you need to display a special warning if your customer is ordering an item that is frequently on backorder, and you've passed in another variable, 'backorder', that specifies this:

%if backorder:
  <span>This item is frequently on backorder</span>
%end

I haven't tested either of these, but I've done similar things using the Django and Flask template engines. I pulled these samples from here:

http://bottlepy.org/docs/dev/tutorial.html#templates

and the 'Bottle Template to Format the Output' section here:

http://bottlepy.org/docs/dev/tutorial_app.html#using-bottle-for-a-web-based-todo-list

Hope this helps!

于 2013-07-25T13:00:18.117 回答