| 제목 | smarty 이용하기. | ||
|---|---|---|---|
| 글쓴이 | emc | 작성시각 | 2009/08/08 07:47:59 | 
|  | |||
| 템플릿 으로 유명한 스마티를 이용해서 view를 컨트롤 하는 방법입니다. 원문은 ci 일본유저 사이트에 있습니다. http://codeigniter.jp/wiki/index.php/Smarty%E3%81%A8%E9%80%A3%E6%90%BA%E3%81%99%E3%82%8B%EF%BC%88UTF-8%E7%B7%A8%EF%BC%89 1. 스마티를 다운받아서 아래 경로에 압축풀기. CodeIgniter/system/libraries/ 2. 스마티의 초기폴더명을「libs」->「smarty」변경. CodeIgniter/system/libraries/smarty 3. smarty_parser.php 파일 생성 CodeIgniter/system/application/config/smarty_parser.php 
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
	// Please see Smarty user guide for more info:
	// http://smarty.php.net/manual/en/api.variables.php
	// The name of the directory where templates are located.
	$config['template_dir'] = dirname(FCPATH);
	// The directory where compiled templates are located
	$config['compile_dir'] = BASEPATH.'cache/';
	//This tells Smarty whether or not to cache the output of the templates to the $cache_dir.
	$config['caching'] = 0;
	// This forces Smarty to (re)compile templates on every invocation.
	// When deploying, change this value to 0
	$config['force_compile'] = 1;
	$config['compile_check'] = TRUE;
?>
※ 캐쉬 파일은 CodeIgniter/system/cache/ 에 저장되고,템플릿 파일은 /system/application/views/에 저장하면 되도록 셋팅하는 것. 4. Smarty_parser.php 파일 생성 CodeIgniter/system/libraries/Smarty_parser.php 
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
require "smarty/Smarty.class.php";
class Smarty_parser extends Smarty {
	function Smarty_parser($config = array())
	{
		parent::Smarty();
		if (count($config) > 0)
		{
		$this->initialize($config);
		}
		// register Smarty resource named "ci"
		$this->register_resource("ci", array($this,
		"ci_get_template", "ci_get_timestamp", "ci_get_secure", "ci_get_trusted")
		);
		log_message('debug', "Smarty_parser Class Initialized");
	}
	/**
	* Initialize preferences
	*/
	function initialize($config = array())
	{
		foreach ($config as $key => $val)
		{
			if (isset($this->$key))
			{
				$method = 'set_'.$key;
				if (method_exists($this, $method))
				{
					$this->$method($val);
				} else {
					$this->$key = $val;
				}
			}
		}
	}
	/**
	* Set the left/right variable delimiters
	*/
	function set_delimiters($l = '{', $r = '}')
	{
		$this->left_delimiter = $l;
		$this->right_delimiter = $r;
	}
	/**
	* Parse a template using Smarty engine
	*
	* Parses pseudo-variables contained in the specified template,
	* replacing them with the data in the second param.
	* Allows CI and Smarty code to be combined in the same template
	* by prefixing template name with "ci:".
	*/
	function parse($template, $data, $return = FALSE)
	{
		if ($template == '')
		{
		return FALSE;
		}
		$CI =& get_instance();
		$CI->benchmark->mark('smarty_parse_start');
		if (is_array($data))
		{
			$this->assign(&$data);
		}
		// make CI object directly accessible from a template (optional)
		$this->assign_by_ref('CI', $CI);
		$template = $this->fetch($template);
		if ($return == FALSE)
		{
			$CI->output->final_output = $template;
		}
		$CI->benchmark->mark('smarty_parse_end');
		return $template;
	}
	/**
	* Smarty resource accessor functions
	*/
	function ci_get_template ($tpl_name, &$tpl_source, &$smarty_obj)
	{
		$CI =& get_instance();
		// ask CI to fetch our template
		$tpl_source = $CI->load->view($tpl_name, $smarty_obj->get_template_vars(), true);
		return true;
	}
	function ci_get_timestamp($view, &$timestamp, &$smarty_obj)
	{
		$CI =& get_instance();
		// Taken verbatim from _ci_load (Loader.php, 580):
		$ext = pathinfo($view, PATHINFO_EXTENSION);
		$file = ($ext == '') ? $view.EXT : $view;
		$path = $CI->load->_ci_view_path.$file;
		// get file modification date
		$timestamp = filectime($path);
		return ($timestamp !== FALSE);
	}
	function ci_get_secure($tpl_name, &$smarty_obj)
	{
		// assume all templates are secure
		return true;
	}
	function ci_get_trusted($tpl_name, &$smarty_obj)
	{
		// not used for templates
	}
}
?>준비완료.5. 스마티이용해보기. 5-1. CodeIgniter/system/application/controllers/smarty_test.php 파일 추가 
<?php
class Smarty_test extends Controller {
	function Smarty_test() {
		parent::Controller();
	}
	function index(){
		//라이브러리 호출
		//config/autoload.php에 설정하면 편리.
                $this->load->library('smarty_parser');
                
                $data['title'] = "템플릿 파일 테스트";
		$data['body'] = "스마티 템플릿으로 테스트 합니다.";
		$this->smarty_parser->parse("ci:template_test.tpl", $data);
	}
}
?>
5-2. view 파일(템플릿) : template_test.tpl 의 생성. CodeIgniter/system/application/views/template_test.tpl 
<h3>{$title}</h3>
<h1>{$body}</h1>
5-3. 실행. http://root/ci/smarty_test/ 이상입니다. 개인적으로는 view에 불필요한 php 코드들이 표시되는것을 안좋아 하는 편입니다. 디자이너와 작업하는 일은 없지만, 뷰는 디자이너도 이해할수 있도록 php 코드가 안나오면 더 좋다고 생각합니다.... ;;; | |||
| 다음글 | .htaccess Editor (2) | ||
| 이전글 | 코딩을 도와주는 폰트 추가요~~~ (8) | ||
| 
                                변종원(웅파)
                                /
                                2009/08/08 08:44:13 /
                                추천
                                0
                             | 
| 
                                ci세상
                                /
                                2009/08/08 10:24:26 /
                                추천
                                0
                             
                                좋은 자료입니다. ^^ CI 템플릿 파서 부분도 왠지 괜찮다는 생각이 드네요 http://codeigniter-kr.org/user_guide/libraries/parser.html 근데 템플릿 파서보다 php직접 코딩이 좀더 빠르다는 내용도 있어서 전 템플릿은 패스했습니다.^^ | 
| 
                                마냐
                                /
                                2009/08/08 13:17:27 /
                                추천
                                0
                             저도 CI세상님과 같은 이유로 패스. | 
| 
                                emc
                                /
                                2009/08/11 10:24:44 /
                                추천
                                0
                             
                                ci 파서도 좋을것 같군요. 스마티에 익숙한 분은 스마티로 이용하세요. 저도 ci로 이용해봐야 겟습니다. | 
| 
                                터프키드
                                /
                                2009/08/26 10:19:28 /
                                추천
                                0
                             
                                Template_ 사용방법도 알려주시면 안될까요?ㅜㅠ 아직도 연동 못하고 있는 1人 ㅠㅠ | 
컨트롤러에서 완벽하게(?) 데이터 처리만 하신다면 ci의 템플릿도 쓸만합니다. ^^