加载在php / codeigniter中的函数内的视图文件 [英] load a view file within a function in php/codeigniter

查看:83
本文介绍了加载在php / codeigniter中的函数内的视图文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我想插入一个视图文件。这很简单,当你只需要 echo 一两个东西,但我有一些复杂的html,所以想利用替代php语法下面的foreach循环和if语句:

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 我更正了 CI-> load->视图根据tpaksu的建议包括第三个参数。它更接近工作,但仍不完全正确。请参阅以下代码中的注释:

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?

推荐答案

我通常在我的项目中使用 snippet_helper 。在这里,我有许多函数可以生成可重用的东西(也称为模块组件)。

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).

我也喜欢,WordPress方法使用返回数据在主要功能(你可能需要更多的治疗显示前)和一个姐妹函数直接 echo 结果。

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

这篇关于加载在php / codeigniter中的函数内的视图文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆