我有一个表,并希望 web2py 操作将其所有内容传递给视图。然后视图从中选择一个子集,并在迭代中一次显示一个。
这是 db.py 中的示例表:
db.define_table('block',
Field('location'),
Field('propertyA'),
Field('propertyB')
)
控制器 default.py 中的示例操作:
def demo():
return dict(blocks=db(db.block).select())
到目前为止,一切都很好。它可以编译,不会崩溃,并且在运行了一些测试后它做了我想要的。
但现在来看。在这个例子中,我想选择所有的“propertyA”,比如说,5。然后我想运行一个循环,将它们打印到一个已经存在的表中。该表有 100 个单元格,ID 为 1-100。我想将 propertyB 的值打印到表单元格中,其 id 与块的位置匹配。
示例视图 default/demo.html:
{{extend 'layout.html'}}
<style>
table#map, td {
border: 1px solid black;
border-collapse: collapse;
}
td {
background-color: gray;
width: 50px;
height:50px;
text-align: center;
color: white;
}
</style>
<!--This creates a 10*10 table with running id from 1 to 100-->
<table id="map">
<caption>Map</caption>
{{for y in range(10):}}
<tr>
{{for x in range(10):}}
{{=TD('', _id=10*y+x)}}
{{pass}}
</tr>
{{pass}}
</table>
<!--then I want to select a subset from blocks, whose propertyA is 5
These lines crash if uncommented.-->
{{#query = (propertyA == 5)}}
{{#subset = blocks(query).select()}}
<!--and run a loop which, which iterates the subset, and in each
iteration, writes the value of propertyB, if cell's id and block's location
match. I just made a place holder function, because I don't know how to
pass python variables/objects to javascript-->
<script>
//var subset = "subset from python";
function myFunction() {
var i;
for (i = 0; i < 100; i++) {
//var cell = document.getElementById(i);
//if(subset(location===cell.id).select() === True) {
//var value = subset(location===cell.id).propertyB;
//cell.innerHTML = value;
//} else {
//cell.innerHTML = '';
//}
}
}
</script>
所以我不知道应该怎么做。而 web2py 教程书对这方面的信息非常吝啬。还是我对此有完全错误的方法?因为我认为它也可以通过 ajax 调用来完成,但我不觉得连续 100 次查询数据库服务器是正确的做法。