Smarty
둘러보기로 가기
검색하러 가기
PHP Template Engine인 smarty를 정리 한다.
- 홈페이지 : http://www.smarty.net/
- 다운로드 : http://www.smarty.net/download.php
- 라이선스 : GNU LGPL
- 플랫폼 : PHP
목차
프로그램 문법
프로그램 기초
- 선언 및 사용
#--- Smarty.class.php 파일이 있는 위치를 나타내는 SMARTY_DIR 상수를 정의 한다. #--- php.ini 파일의 include_path에도 추가 되어 있어야 한다. #--- $compile_dir과 $cache_dir에 대한 읽고 쓰기 권한이 있어야 한다. define('SMARTY_DIR', '/var/www/html/sugar/include/Smarty'); require_once('Smarty.class.php'); $smarty = new Smarty(); $smarty->template_dir = '.'; $smarty->compile_dir = '/var/www/html/sugar/cache/smarty/templates_c/'; $smarty->config_dir = '/var/www/html/sugar/cache/smarty/configs/'; $smarty->cache_dir = '/var/www/html/sugar/cache/smarty/cache/'; $smarty->assign('firstname', 'Doug'); ### $str = $smarty->fetch('index.tpl'); $smarty->display('index.tpl');
상수/변수
- 내장 상수
SMARTY_DIR SMARTY_CORE_DIR
- Smarty 클래스 변수
$debugging $debug_tpl $debugging_ctrl $autoload_filters $compile_check $force_compile $caching $cache_lifetime $cache_handler_func $cache_modified_check $config_overwrite $config_booleanize $config_read_hidden $config_fix_newlines $default_template_handler_func $php_handling $security $secure_dir $security_settings $trusted_dir $compiler_class $request_vars_order $request_use_auto_globals $error_reporting $compile_id $use_sub_dirs $default_modifiers $default_resource_type
- Smart 문법이 적용되는 Delimiter 정의
$left_delimiter : Default 값. { $right_delimiter : Default 값. }
- Smarty에서 사용하는 디렉토리리를 지정 한다.
$template_dir $compile_dir $config_dir $plugins_dir $cache_dir
함수
- Smart 클래스 함수
append() -- 할당된 템플릿 배열에 요소를 추가합니다. append_by_ref() -- 참조로서 값을 추가합니다. assign() -- 템플릿에 값을 할당합니다. assign_by_ref() -- 참조로서 값을 할당합니다. clear_all_assign() -- 할당된 모든 템플릿 변수를 파기합니다. clear_all_cache() -- 모든 템플릿의 캐시를 파기합니다. clear_assign() -- 할당된 템플릿 변수의 값을 파기합니다. clear_cache() -- 지정한 템플릿의 캐시를 파기합니다. clear_compiled_tpl() -- 지정한 템플릿의 캐시를 파기합니다. clear_config() -- 할당된 모든 설정 파일의 변수를 파기합니다. config_load() -- 설정 파일 데이터를 로딩하여, 템플릿에 할당합니다. display() -- 템플릿을 표시합니다. fetch() -- 템플릿의 출력을 반환합니다. get_config_vars() -- 로딩된 설정 파일 변수를 반환합니다. get_registered_object() -- 등록된 오브젝트의 참조를 반환합니다. get_template_vars() -- 할당된 변수의 값을 반환합니다. is_cached() -- 템플릿이 유효한 캐시를 가질 경우에 TRUE를 반환합니다. load_filter() -- 필터 플러그인을 로딩합니다. register_block() -- 블록 함수 플러그인을 동적으로 등록합니다. register_compiler_function() -- 컴파일러 함수 플러그인을 동적으로 등록합니다. register_function() -- 템플릿 함수 플러그인을 동적으로 등록합니다. register_modifier() -- 변수의 변경자 플러그인을 동적으로 등록합니다. register_object() -- 템플릿 내에서 사용할 오브젝트를 등록합니다. register_outputfilter() -- 출력 필터를 동적으로 등록합니다. register_postfilter() -- 포스트 필터를 동적으로 등록합니다. register_prefilter() -- 프리 필터를 동적으로 등록합니다. register_resource() -- 리소스 플러그인을 동적으로 등록합니다. trigger_error() -- 에러 메시지를 출력합니다. template_exists() -- 지정한 템플릿이 존재하는지 아닌지를 체크합니다. unregister_block() -- 동적으로 등록된 블록 함수 플러그인의 등록을 해제합니다. unregister_compiler_function() -- 동적으로 등록된 컴파일러 함수의 등록을 해제합니다. unregister_function -- 동적으로 등록된 템플릿 함수 플러그인의 등록을 해제합니다. unregister_modifier() -- 동적으로 등록된 변수의 변경자 플러그인의 등록을 해제합니다. unregister_object() -- 동적으로 등록된 오브젝트의 등록을 해제합니다. unregister_outputfilter() -- 동적으로 등록된 출력 필터 플러그인의 등록을 해제합니다. unregister_postfilter() -- 동적으로 등록된 포스트 필터 플러그인의 등록을 해제합니다. unregister_prefilter() -- 동적으로 등록된 프리 필터 플러그인의 등록을 해제합니다. unregister_resource() -- 동적으로 등록된 리소스 플러그인의 등록을 해제합니다.
데이터 할당
$smarty->assign('firstname', 'Doug');
기타 확장 문법
- Template Cache
- 캐시
- 캐시 핸들러 함수
- 오브젝트 : PHP Object로의 접근 허용
- Filter : Pre_Filter, Post_Filter, Output_Filter
function func_prefilter($tpl_source, &$smarty) { return preg_replace("//U",,$tpl_source); } $smarty->register_prefilter('func_prefilter'); $smarty->register_postfilter('func_postfilter'); $smarty->register_outputfilter('func_outputfilter');
- 템플릿 리소스 : 파일외에 장소로부터 Template을 가져오고 싶을 때 사용
- Plugin
- Smarty의 대부분의 기능을 Plugin Architecture를 사용하여 확장 가능
- Plugin type
- function : 템플릿 함수 플러그인
- modifier : 변경자 플러그인
- block : 블록 함수 플러그인
- compiler : 컴파일러 함수 플러그인
- prefilter : 프리 필터 플러그인
- postfilter : 포스트 필터 플러그인
- outputfilter : 출력 필터 플러그인
- resource : 리소스 플러그인
- insert : insert 플러그인
- Plugin 명명 규칙
- 파일 명명 규칙 : type.name.php
- 함수 명명 규칙 : smarty_type_name($params, &$smarty)
- Plugin 등록
require_once $smarty->_get_plugin_filepath('function', 'html_options');
Template 문법
Template 기초
- Script의 시작과 끝
{ }
- 주석
{* ~ *}
- Template 무시 (Template을 적용하지 않음)
{literal} ~ {/literal}
- PHP 코드 포함
{php} ~ {/php}
- white space와 carriage return을 제외하고 브라우저에 전달
{strip} ~ {strip}
- 변수 사용
- "" 내에서 변수를 사용할 때는 ``로 묶어 준다.
예) {func var="test `$foo.bar` test"}
Template 상수/변수
- 내장 상수
- 변수 선언
{assign var='name' value='Bob'}
- Smarty 내장 변수 : {$smarty}
{$smarty.request.username} {$smarty.get.page}, {$smarty.post.page} {$smarty.cookies.username} {$smarty.env.PATH} {$smarty.session.id} {$smarty.server.SERVER_NAME} : $_SERVER['SERVER_NAME'] {$smarty.now} {$smarty.const} {$smarty.capture} {$smarty.config} {$smarty.section},{$smarty.foreach} {$smarty.template} {$smarty.version} {$smarty.ldelim},{$smarty.rdelim}
- PHP 프로그램에서 넘겨 받은 변수
{$foo} {$foo[4]} : 배열의 index는 0부터 시작함 {$foo.bar}, {$foo.$bar} : $foo['bar'], $foo[$bar] {$foo->bar}, {$foo->bar()} : Object내의 변수 및 함수 지정 {#foo#} : Config_File.class.php 내의 변수, {$smarty.config.foo}
- 변수의 변경자
- 사용 문법 : {$변수|변경자1: 변경자 1용 파라메터|변경자2|변경자3}
capitalize cat count_characters count_paragraphs count_sentences count_words date_format default escape indent lower nl2br regex_replace replace spacify string_format strip strip_tags truncate upper wordwrap
Template 함수
- 함수 사용 문법
{funcname attr1='val1' attr2='val2'}
- 내장 함수
{capture} {config_load} : Configure 파일 로딩 {foreach},{foreachelse} : {foreach from=$data key=name item=value} {$name} {$value} {/foreach} {if},{elseif},{else} {include} {include_php} {insert} {literal} {php} {section},{sectionelse} {strip}
- Smart 문법이 적용되는 Delimiter 정의
{ldelim} : Default 값. "{" {rdelim} : Default 값. "}"
- 외장 함수 : Plugin을 경유하여 실행되는 함수
{assign} {counter} : 숫자를 헤아린다. {cycle} : 값을 반복 순환 한다. {debug} : 화면에 Debug 정보를 표시 한다. {eval} {fetch} {math} {popup_init}, {popup} {textformat} : 텍스트의 포맷을 지정하여 보여 준다.
- HTML 문을 생성하는 외장 함수
{html_checkboxes} {html_image} {html_options} {html_radios} {html_select_date} {html_select_time} {html_table} {mailto}
- config_load
- test.config
#global pageTitle="Hello" [login] pageTitle="Login"
- Template
{config_load file="test.conf" section="login"} {#pageTitle#} {$smarty.config.pageTitle}
Template 포함
- 외부 Template 파일 포함
{include file='get_banner.tpl'} {include_php file='/path/to/load_nav.php'} {insert name="getBanner" lid=#banner_location_id# sid=#site_id#} : Cache되지 않음
- 내부 Capture 영역 포함
{capture name=banner} {include file='get_banner.tpl'} {/capture} {$smarty.capture.banner}
- 외부 파일 포함
{fetch file='/export/httpd/www.example.com/docs/navbar.js'} {fetch file='ftp://user:password@ftp.example.com/path/to/currentheadlines.txt'} {fetch file='http://www.myweather.com/68502/' assign='weather'}
Template 분기 및 순환
- if 문
- 연산자 : ==, !=, >, <, >=, <=, ===, !, %
{if $name eq 'Fred'} Welcome Sir. {elseif $name eq 'Wilma'} Welcome Ma'am. {else} Welcome, whatever you are. {/if}
- foreach 문
{foreach from=$myArray item=foo} {$foo} {$smarty.foreach.foo.first} : 최초 반복일 경우 true {$smarty.foreach.products.last} : 마지막 반복일 경우 true {$smarty.foreach.foo.index} : for 배열의 인덱스 (0, 1, 2, ...) {$smarty.foreach.foo.iteration} : foreache문이 반복된 횟수 (1, 2, 3, ...) {$smarty.foreach.foo.total} : 반복할 전체 횟수 {foreachelse} {/foreach} {foreach from=$myArray key=name item=value} {$name}: {$value} {foreachelse} {/foreach}
- section 문
{section name=customer loop=$custid} id: {$custid[customer]} {sectionelse} {/section} {section name=foo loop=$custid step=-1} {$custid[foo]} {/section}
Template 확장 문법
Smarty 분석
- 배열 표시
{{foreach from=$detail_header_buttons key=name item=value}}
ppp : {$name} : {$value} <br/>
{{/foreach}}
- 배열의 배열 표시
{ {foreach from=$detail_header_buttons key=parentName item=parentValue} } Parent : {$parentName}
{ {foreach from=$parentValue key=name item=value} } ppp : {$name} : {$value}
{ {/foreach} } { {/foreach} }