php - 如何简化 CI 中 View 的冗余调用

标签 php html codeigniter

在我的应用程序中,页眉和页 footer 分几乎总是静态的。中间部分包含我加载到 View 然后将其附加到页眉和页脚 View 的动态数据。

示例:

View /标题:

<html>
<head><titile>My App</title></head>
<body>

View /页脚

</body>
</html>

Controller

public function page1($contents){

$page  = $this->load->view('header',null,true);
$page .= '<div>' . $contents . '</div>';
$page .= $this->load->view('footer', null, true);

echo $page;
}

上面的示例可能看起来过于简单,但如果我的静态 View 不仅仅是页眉和页脚,那么每当我需要构建 View 时,代码就会变得非常冗余。有什么办法可以在函数中简化它吗? (最好在库中创建一个类)

最佳答案

您可以在 CORE 中创建一个 MY_controller 扩展并在其中定义一个函数来完成此操作,但如果您更喜欢在 LIBRARY 中使用它,则创建一个这样的类:

Class Viewer(){

     public function __construct(){
          // CREATE AN INSTANCE OF THE CONTROLLER CLASS LIBRARY
          $this->CI =& get_instance(); 
    }


     // Where $content is your dynamic content from another view; 
     public function final_view($content){
        $final_view  =  $this->CI->load->view('header',null,true);
        $final_view .=  $content;
        $final_view .=  $this->CI->load->view('footer',null,true);

        return $final_view;
       }
}

在你的 Controller 上,重新使用上面的代码:(假设你已经自动加载库查看器 auto-loading in CodeIgniter );

public function page1($contents){

     $dynamic_content = '<div>' . $contents . '</div>';
     echo $this->viewer->final_view($dynamic_content);
}

在不同的功能上,你可以做同样的事情

public function page2($more_contents){

     $dynamic_content = '<h1>' . $more_contents . '</h1>';
     echo $this->viewer->final_view($dynamic_content);
}

如果这有帮助,请告诉我!

关于php - 如何简化 CI 中 View 的冗余调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36360407/

相关文章:

php - 显示数据库值?

jquery - CSS 动画在 IE 中不起作用

html - 具有 float 和最大宽度问题的网格系统

php - 未能删除缓冲区。没有要删除的缓冲区

php倒计时服务器端

php - 将邮件通过管道传输到 PHP 时提取附件

PHP MySQL : Getting rows from table A where values of column Z of Table A not present in column Z of table B

javascript - 绝对定位布局 - 垂直居中于前一个 div

mysql - Codeigniter 数据库加入不接受值而不是列名

php - Laravel 框架对于中型项目是否足够稳定,还是我应该坚持使用更稳定的 Yii?