질문Q #8193
layout을 사용할때 view안에 css넣기
니삼2013-10-22 22:24:43
layout을 이용해 view를 구성하면 content영역을 담당하는 view안에 css나 js 혹은 title을 넣기가 난감해집니다.

ex) layout.php
<html>
<head>
<?php css 출력 ?>
</head>
<body>
<?php echo $layout_content; ?>
</body>

이런식으로 컨트롤러에서 css 파일명을 받아서 css폼에 맞게 출력하거나 했습니다.

그러나 css나 js는 따지고 보면 view영역이라 단순 view페이지라면 컨트롤러에서 넘겨주는건 좀 껄끄러웠습니다.


결론 : 

view : index.php
<head>
<script>alert('test');</script>
...css 등 삽입
</head>
<body>
<div>body</div>
</body>

이렇게 구성하여 view 페이지에 <head> 태그와 body 태그를 이용해 컨텐츠를 구성하고

view/layout.php
<html>
<head>
<?php echo $head; ?>
</head>
<body>
<?php echo $body; ?>
</body>
</html>

layout.php를 만들어 레이아웃을 지정합니다.

libraries/Layout.php
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Layout
{

    var $obj;
    var $layout;

    function __construct($layout = "layout")
    {
        $this->obj =& get_instance();
        $this->layout = $layout;
    }

    function setLayout($layout)
    {
        $this->layout = $layout;
    }

    function view($view, $data=null, $return=false)
    {
        $loadedData = array();
        $tmp_view = $this->obj->load->view($view,$data,true);

        preg_match('/<body>(.*)<\/body>/s',$tmp_view, $body);
        preg_match('/<head>(.*)<\/head>/s',$tmp_view, $head);
        $loadedData['body'] =  $body[1];
        $loadedData['head'] = $head[1];

        if($return)
        {
            $output = $this->obj->load->view($this->layout, $loadedData, true);
            return $output;
        }
        else
        {
            $this->obj->load->view($this->layout, $loadedData, false);
        }
    }
}
?>
널리 퍼진 레이아웃 라이브러리를 살짝 수정해서 중간에 view를 요리 합니다.

controllers/index.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        //라이브러리 로드(저는 오토로드 설정)
        //$this->output->enable_profiler(TRUE);
    }

    public function index()
    {
        $this->layout->view('index');
    }
}
레이아웃 라이브러리를 통해 view를 호출합니다.

결과:
<html>
<head>

    <script>alert('test');</script>
</head>
<body>

<div>body</div>
</body>
</html>

엔터가 같이 삽입됬지만 우선은 넘어갑니다. 
이렇게 구성하면 view에 css,js(js는 하단에 넣을 수도 있겠죠) 등을 배치하여 컨트롤러에서 css,js를 설정하지 않아도 view에서 가지오게 됩니다.


(사실 tip을 가장한 아이디어를 듣고 싶어서 적습니다ㅠ 이 방식에 대한 의견을 듣고 싶습니다(?))
답변1
#1 변종원(웅파) 2013-10-23 17:33:25
아이디어 좋네요.

이제 레이아웃을 hook포인트가 아니라 컨트롤러로 가지고 오면 좀더 재미있게 만들 수 있습니다. ^^