load a view file within a function in php/codeigni

2019-06-01 03:31发布

问题:

I have a function that I'd like plug a view file. It's pretty simple when you just need to echo one or two things but I have some complicated html and so would like to take advantage of alternate php syntax for the following foreach loop and if statements:

UPDATE I corrected the CI->load->view to include the 3rd parameter according to tpaksu's suggestion. It's closer to working but still not quite right. See comments below in the code:

<?
  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);        
?>

Here's what the 'reviews/comment list view file looks like in its simplest form:

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

Would anyone know to how embed view files into a function?

回答1:

I usually use to have a snippet_helper in my projects. There, I have many many functions wich generates chunks of reusable things (also called modules or components).

I do like, also, the WordPress approach wich use to return data in the main function (you may need more treatments before display) and a "sister function" to directly echo the results.

I think it'll works with you. For example:

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);
}


回答2:

Your content on the first file :

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

And the reviews/comment_list view :

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

just write this and try again.