开发者

Symfony: recursive call in template

I need to render a nested set tree as a li-structure with unlimited depth. While I unde开发者_如何学JAVArstand how to do it in plain php (like here: PHP: How to generate a <ul><li> tree in an xml2assoc array result?), I hate echoing html tags and would like to have it done in a template. Is it possible with PHP as a templating language? Where should I define a recursive function?


For me, I depends on how much 'code' is needed in each iteration.

For simple trees, I would just declare a function at the top of the view-file. (Since I think that function has only real value in that separate file).

For trees with a bit more rendering, I would create a separate partial file. That file could be called in the view file and in the partial file itself.

You could also create a helper file, which you use on that specific page, put than the partial would make more sense and is easier to implement (and you can use all other helper functions and symfony functions)


hm, here is my sollution:

<?php
/**
 * @var $records
 * @var $field
 */
?>

<?php if( isset($records) && is_object($records) && count($records) > 0 ): ?>
  <div id="document-nested-set">
    <ul class="nested_set_list">
    <?php $prevLevel = 0; $is_first = true; ?>
    <?php foreach($records as $record): ?>
      <?php if($prevLevel > 0 && $record['level'] == $prevLevel)  echo '</li>';
      if($record['level'] > $prevLevel)  echo '<ul>';
      elseif ($record['level'] < $prevLevel) echo str_repeat('</ul></li>', $prevLevel - $record['level']); ?>
      <?php $rel = $record['lft']=='1'?'root':($record['is_approved'] && $record['is_checked']?'document':'document_grey') ?>
      <li id ="phtml_<?php echo $record->id ?>"  rel="<?php echo $rel ?>" <?php echo $is_first?'class="open"':'' ?>>
          <a href="#"><ins>&nbsp;</ins><?php echo $record->$field;?></a>
      <?php $prevLevel = $record['level']; $is_first = false; ?>
    <?php endforeach; ?>
    </ul>
  </div>
<?php endif;?>


an easy example:

<?php
    $input = array('c' => array('c1' => 't1', 'c2' => array('c21' => array('c211' => 't2'), 'c22' => 't3')));

    $iterate = function($array) use (&$iterate) {
        $out = '<ul>';
        foreach($array as $key => $child)
            $out .= '<li>'.$key.': '.( is_array($child) ? $iterate($child) : $child ).'</li>';
        return $out.'</ul>';
    }
?>

<html><body><?php echo $iterate($input); ?></body></html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜