2010-10-04 63 views
2

爲簡單起見,假設我有一個列表列表。我想要顯示一個html表,其中頂級列表的每個元素都有一行,並且該行中的每一列都是子列表的一個元素。如何使用未知(在構建時)的列數創建表格

所以

List(List(1,2,3), List(4,5,6), List(7,8,9)) 

會導致在顯示這樣一個HTML表格:

1  2  3 
4  5  6 
7  8  9 
10 11 12 

這是我嘗試(模板)

<table> 
     <lift:viewQuery.res2> 
      <tr> 
      <a:row> 
       <td><a:num/></td> 
      </a:row> 
      </tr> 
     </lift:viewQuery.res2> 
    </table> 

,並在相關方法摘錄:

def res2(in :NodeSeq) : NodeSeq = { 
    val data = List(List(1,2,3), List(4,5,6), List(7,8,9), List(10,11,12)) 

    def bindChild(child : List[Int],in :NodeSeq) = { 
    child.flatMap(c => Helpers.bind("a", in, 
            "num" -> c.toString)) 
    } 
    data.flatMap(childList => Helpers.bind("a", in, 
             "row" -> bindChild(childList, in))) 
} 

當我去它給了我下面的錯誤頁面:

error on line 28 at column 23: Namespace prefix a on row is not defined 
error on line 29 at column 31: Namespace prefix a on num is not defined 
error on line 34 at column 23: Namespace prefix a on row is not defined 
error on line 35 at column 31: Namespace prefix a on num is not defined 
... 

任何想法在處理這個最好的方法是什麼?

回答

2

你就近了。試試這個:

<table> 
    <lift:viewQuery.res2> 
     <a:row> 
     <tr> 
      <b:cell><td><cell:num/></td></b:cell> 
     </tr> 
     </a:row> 
    </lift:viewQuery.res2> 
</table> 

併爲您的片段:

def res2(in :NodeSeq) : NodeSeq = { 
    import Helpers._ 
    val data = List(List(1,2,3), List(4,5,6), List(7,8,9), List(10,11,12)) 

    def cell(x: List[Int])(template: NodeSeq) = 
    x.flatMap{y: Int => bind("cell", template, "num" -> y) } 
    def row(x: List[List[Int]])(template: NodeSeq) = 
    x.flatMap {y => bind("b", template, "cell" -> { x: NodeSeq => cell(y)(x)}) } 

    bind("a", in, "row" -> { x: NodeSeq => row(data)(x) }) 
} 

我已經離開在某些類型的和已經更加明確了一點,所以你可以清楚地看到是怎麼回事。你的問題是你在每個級別使用相同的模板in,當你想要做的是逐步縮小模板。因此,在上面的模板中,我們希望<a:row>標籤內的所有內容都對列表中的每個頂級項目重複執行,然後<b:cell>中的所有內容都可以爲每個Int重複一次。做到這一點的方法是創建一個FuncBindParam這是我們與以下行做什麼:那麼

"row" -> { x: NodeSeq => row(data)(x) } 

電梯會通過在被包含在<a:row>標記中作爲參數傳遞給了令行禁止的XHTML功能。並且在curried函數內調用flatMap會根據需要多次重複模板。

2

如果您不需要特定的電梯應答,這樣的事情可以工作

val data = List(List(1,2,3), List(4,5,6), List(7,8,9)) 
<table>{data.map(row => <tr>{row.map(col => <td>{col}</td>)}</tr>)}</table> 

您的實際使用情況可能會更復雜一點的,所以這可能不適用。

+0

是的,這個工程,我希望有一些更乾淨。 – jmo 2010-10-08 16:44:22

相關問題