1

我有一个要插入视图文件的功能。当您只需要echo一两件事但我有一些复杂的 html 时,这非常简单,因此想为以下 foreach 循环和 if 语句利用备用 php 语法:

更新CI->load->view根据 tpaksu 的建议更正了包含第三个参数。它更接近工作,但仍然不太正确。请参阅代码中的以下注释:

<?
  function displayComments(array $comments, $parentId = null) {
  $CI=& get_instance();     
  foreach($comments as $comment){
        if($comment['replied_to_id'] == $parentId){

     echo $CI->load->view('reviews/comment_list', $comments, true); // this doesn't work, it only shows the last array member
              // echo $comment['comment']; this works as expected
    }
   }
  }  
displayComments($comments, $parentId = null);        
?>

以下是“评论/评论列表视图文件”最简单的形式:

<ul> 
 <? foreach($comments as $comment): $comment=$comment['comment']?>
  <li>
      <?echo $comment?>
 </li> 
 <?endforeach;>
</ul>

有人知道如何将视图文件嵌入到函数中吗?

4

2 回答 2

1

您在第一个文件中的内容:

<?php
    $CI=& get_instance();     
    echo $CI->load->view('reviews/comment_list', $comments, true);
?>

reviews/comment_list观点:

<ul> 
    <?php
    foreach($comments as $comment){
       $comment=$comment['comment'];
       echo "<li>" . $comment . "</li>";
    }
    ?>
</ul>

写这个然后再试一次。

于 2012-04-30T05:34:53.327 回答
1

我通常在我的项目中有一个snippet_helper 。在那里,我有很多函数可以生成大量可重用的东西(也称为模块组件)。

我也喜欢在主函数中返回数据的 WordPress 方法(在显示之前您可能需要更多处理)和直接echo结果的“姐妹函数”。

我想它会和你一起工作。例如:

function get_display_comments(array $comments, $parentId = NULL)
{
    $CI     =& get_instance();
    $return = '';

    foreach ($comments AS $comment)
    {
        if ($comment['replied_to_id'] == $parentId)
        {
            $return .= $CI->load->view('reviews/comment_list', $comments, TRUE);
        }
    }

    return $return;
}

function display_comments(array $comments, $parentId = NULL)
{
    echo get_display_comments($comments, $parentId);
}
于 2012-05-01T13:26:38.427 回答