在drupal视图中创建的行太多

时间:2011-10-31 14:24:40

标签: php drupal drupal-7

我修改了用于网格视图的tpl以显示3列内容,我唯一的问题是下面的代码为视图创建了不需要的div。我最多有9个项目应该以3行输出,每列3个。修改下面代码的最佳方法是什么?防止额外的div输出。

<?php foreach ($rows as $row_number => $columns): ?>
  <div>
    <?php foreach ($columns as $column_number => $item): ?>

        <?php print $item; ?>

    <?php endforeach; ?>
  </div>
<?php endforeach; ?>

1 个答案:

答案 0 :(得分:0)

我会删除foreach语法的符号(但我认为这非常个人化:-))

您可以使用模数来检查您是否只有3列(如果我理解您的问题)。

<?php

// I´m assuming that $column_number is a zero based index
// if thats not the case you should add a counter to keep track of column numbers or if it is in sequence but isn't zero based you could easily update the calculates based in your starting index

foreach ($rows as $row_number => $columns) {
    foreach ($columns as $column_number => $item) {
        if ($column_number == 0 || $column_number%3 == 0) {
            print '<div>';
        }
        print $item;
        if ($column_number == 2 || $column_number%3 == 2) {
            print '</div>';
        }
    }
    // prevent open div tags
    $total_columns = count($columns);
    if ($total_columns > 0 && ($total_columns < 3 || $total_columns%3 != 0)) {
        print('<div>');
    }
}

为了便于阅读,我还放弃了所有那些打开和关闭的标签。