zkzk-grid

How to iterate models in zk over even index?


I need to display objects in a model row-wise, with two models in each row. In my zul file I have to group the models in groups of two. How is it possible using foreach, foreachstatus or template ? I am using zk grid


Solution

  • Here is an example witch switch between 2 templates on the index.
    You just have to implement the modulo 2 and check for 1 or 0.

    http://www.zkfiddle.org/sample/2rjaqos/4-MVVM-with-nested-template

    zul code of that link :

    <listbox model="@load(vm.beans)">
            <listhead children="@load(vm.colTitle)">
                <template name="children" var="title">
                    <listheader label="@load(title)" />
                </template>
            </listhead>
            <template name="model" var="bean">
                <listitem children="@load(vm.colTitle)  @template(forEachStatus.index lt 1 ? 'fixed' : 'variable')">
                    <template name="fixed">
                        <listcell label="@load(bean.title)" />
                    </template>
                    <template name="variable">
                        <listcell>
                            <checkbox checked="@load(bean.states[forEachStatus.index - 1])"
                                label="@load(bean.states[forEachStatus.index - 1] ? 'true' : 'false')"
                                onCheck="@command('onCheckState', bean=bean, state=self.isChecked(), index=forEachStatus.index - 1)" />
                        </listcell>
                    </template>
                </listitem>
            </template>
    </listbox>
    

    here another example with the modulo but with 1 template :
    http://zkfiddle.org/sample/2pmngjk/9-Listbox-with-Template

    Zul code of second example :

    <zk>
      <window apply="pkg$.FruitProvider">
              <listbox model="${$composer.fruits}">
                      <template name="model">
                              <listitem>
                                      <listcell if="${forEachStatus.index % 2 == 0}">
                                              <textbox value="${each[0]}" />
                                              <textbox value="${each[1]}" />
                                      </listcell>
                                      <listcell unless="${forEachStatus.index % 2 == 0}">
                                              <label value="${each[0]}" />
                                              <label value="${each[1]}" />
                                      </listcell>
                              </listitem>
                      </template>
              </listbox>
      </window>
    </zk>