CI 코드

제목 Template 엔진
글쓴이 letsgolee 작성시각 2014/10/23 14:00:42
댓글 : 3 추천 : 0 스크랩 : 0 조회수 : 23352   RSS
간단한  템플릿 엔진을 만들었습니다. 누군가에게는 도움이 될 것같아 공개합니다. 근데 테스트는 안해보았네요...
 
load->library('template');
 * $this->template->set_default_path(FCPATH.'templates/'); // default is APPPATH.'templates/'
 * $data = array('title'=>'My Title', 'name'=>'My Name');
 * $this->template->set($data);
 * $this->template->buffer('content', 'page/contents_html'); // it will parse 'page/contents_html.php' in the $_default_path;
 *                                                           // and then add to the variable 'content'.
 * $this->template->render('layout'); // finally layout.php will be output.
 *
 * or you can use the chain style
 * $this->template->set_default_path(FCPATH.'templates/')->set($data)->buffer('content', 'contents_html')->render('layout');
 *
 */
if (!defined('PHP_EXT')) {
    define('PHP_EXT', '.php');
}
class Template
{
	protected $CI = NULL;

	protected $_default_path = '';

	protected $_view_data = array();

	protected $_error_messages = array();

	function __construct($path='')
	{
		if (function_exists('get_instance') && defined('APPPATH')) {
			// this is CI...
			$this->CI =& get_instance();

			if (strlen($path)) {
				$this->set_default_path($path);
			} else {
				$this->_default_path = APPPATH.'templates/';		
			}
		}

		log_message('debug', 'Template Class Initialized');
	}

	public function set_default_path($path)
	{
		if (is_dir($path)) {
			$this->_default_path = rtrim($path, '/').'/';
		} else {
			$this->_error_messages[] = 'The given path is not a real directory.';
			log_message('debug', 'Template Error: The given path is not a real directory.');
		}
		return $this;
	}

	public function set($key, $value=NULL)
	{
		if (is_array($key)) {
			foreach ($key as $k => $v) {
				$this->_view_data[$k] = $v;
			}
		} else {
			$this->_view_data[$key] =$value;
		}

		return $this;
	}

	public function assign($key, $value=NULL)
	{
		return $this->set($key, $value);
	}

	public function buffer($key, $view)
	{
		if ($buffer = $this->_load_view($view, TRUE)) {
			$this->_view_data[$key] = $buffer;

		}
		return $this;
	}

	public function render($view, $data=NULL)
	{
		if (is_array($data)) {
			foreach ($data as $key => $value) {
				$this->_view_data[$key] = $value;
			}
		}

		return $this->_load_view($view);
	}

	protected function _load_view($view, $return_result=FALSE)
	{
		// If the PHP installation does not support short tags we'll
		// do a little string replacement, changing the short tags
		// to standard PHP echo statements.
		$view_file = $this->_default_path.$view.PHP_EXT;
		if (is_file($view_file)) {
			ob_start();
			extract($this->_view_data);

			if ( ! is_php('5.4') && ! ini_get('short_open_tag') && config_item('rewrite_short_tags') === TRUE) {
				echo eval('?>'.preg_replace('/;*\s*\?>/', '; ?>', str_replace('CI) {
				$this->CI->output->append_output($buffer);
			} else {
				// display it
				echo $buffer;
			}
			@ob_end_clean();
		} else {
			$this->_error_messages[] = $view_file.' is not a file or does not exist';
			log_message('DEBUG', $$view_file.' is not a file or does not exist');
		}
	}

	function error_message()
	{
		if (count($this->_error_messages)) {
			$message = array_pop($this->_error_messages);
			return $message;
		} else {
			return FALSE;
		}
	}
}

사용법은 다음과 같습니다:

// 라이브러이 로드
$this->load->library('template');

// 디폴트 템플릿 위치설정
// 기본값은 APPPATH.'templates/'입닏다.
$this->template->set_default_path(FCPATH.'templates/myskin/');

// 데이터
$data = array('title'=>'My Title', 'name'=>'My Name');

// 데이터 assign
// set()을 써도 되고 assign()을 써도 됩니다. 편한대로...
// array가 온 경우
$this->template->set($data);
// 단일 assign
$this->template->assign('message', '만나서 반가움...');

// 페이지를 포함하고 싶을 때는 buffer()를 사용하여 변수로 등록합니다.
// 디폴트 폴더로 지정한 곳에 있는 page/contents_html.php를 불러와서
// content라는 변수로 할당
$this->template->buffer('content', 'page/contents_html');

// 최종 렌더링
// 디폴트 폴더에 있는 layout.php 파일을 불러와 화면에 디스플레이
$this->template->render('layout');

// 체인방법도 가능합니다.
$this->template->set_default_path(FCPATH.'templates/')->set($data)->buffer('content', 'contents_html')->render('layout');
 다음글 컨트롤러에서 컨트롤러 사용 (10)
 이전글 로그를 개발자 도구 콘솔창에서 보자 (2)

댓글

한대승(불의회상) / 2014/10/23 14:57:43 / 추천 0
수고 하셨습니다. ^^
코드가 군더더기 없이 깔끔하네요
letsgolee / 2014/10/23 17:05:16 / 추천 0
@한대승
감사합니다^^
방문넷 / 2022/12/24 23:52:27 / 추천 0
5년동안 잘 사용하였습니다 ㅎ