phpsource/템플릿2006. 9. 15. 09:44
written: Oct 13 2006
필터 정보
$tpl = new hTemplate(템플릿 파일 기본 디렉토리, 캐시 정보, HTML 파서 정보,
array(
'allow_filter' => 필터함수목록
)
);
후키템플릿 생성자의 네 번째 인수로 필터 정보가 전달됩니다.
allow_filter
'allow_filter' => 필터함수목록
생성자에서 지정된 허용필터명령은 모든 템플릿문서에 적용됩니다.
[code php;gutter:false] $tpl = new hTemplate( array( $theme_dir ), array( 'path' => $cache_dir, 'id' => $tpl_id ), array( 'active_tag_lowercase' => false ), array( 'allow_filter' => 'func_a, func_c, func_d, func_e, =' ) ); [/code]
"="를 지정하면 php명령과 전처리명령을 사용할 수 있습니다. "="를 제외한 "func_a", "func_c", "func_d", "func_e"는 허용되는 사용자정의 필터함수를 의미합니다. 필터상수와 내장필터함수는 아무런 제한없이 모든 템플릿문서에서 사용할 수 있습니다.
특별히 허용필터명령을 지정하지 않으면 모든 필터명령(필터상수, php명령, 전처리명령, 사용자정의 필터함수 및 내장필터함수)을 사용할 수 있습니다.
허용필터명령을 지정하지 않을 때
허용필터명령을 지정하지 않으면 모든 필터명령을 제한없이 사용할 수 있습니다.

Posted by 방글24
phpsource/템플릿2006. 8. 2. 13:07
written: Oct 26 2006
[버전1.2.0 제안서] 여기서 기술한 내용은 확정된 용법이 아니라 다음 버전을 발표할 때까지 여러분의 의견 수렴을 통해 더 검토되어야 하는 제안서(proposal)로 문법적인 내용이 다소 변경될 수 있음을 미리 밝혀둡니다.
다음 버전부터는 필터 기능을 지원하지 않습니다. 필터기능은 다른 방법으로 단순화시켜 제공할 생각입니다.
필터명령 실행시간
필터명령의 실행시간은 아래와 같은 지시자에 의해 변경될 수 있으며, 또한 혼용되어 사용될 수 있습니다.
① initialize
② premacro
③ precompile
④ compile
⑤ postcompile
⑥ preassign
⑦ assign
⑧ postassign
⑨ output
블록변수를 포함한 모든 템플릿변수의 필터명령 실행시간을 정리하면 아래표와 같습니다.
< 필터명령 실행시간 >
실행시간 단순
변수
조건
변수
블록변수 파일변수
tpl txt php tpl txt php
initialize x x x x x o x x
premacro x x x x x o x x
precompile x x o o o o o o
compile x x x x x x x x
postcompile x x o x x o x x
preassign x x o x x o x x
assign @ @ x x x x x x
postassign x x @ @ @ @ @ @
output x x x x x o x x
x : 실행시간 지정불가, o : 실행시간 지정가능, @ : 실행시간 지정가능(default)
tpl=template, txt=text document, php=php script
블록변수/파일변수에 필터명령 실행시간(execute time)을 지정하지 않으면(default 상태) 블록내용/파일내용을 assign한 직 후(postassign)에 필터링합니다. 반면 단순변수/조건변수는 assign할 때 필터링합니다. 이와 같이 각 템플릿 변수별로 실행시간 초기값이 지정되어 있습니다.
위 표의 기준과 다르게 예외적으로 compile 실행시간으로 처리되는 요소들은 아래와 같습니다.
① 필터상수(filter constants)
② 파일변수의 파일명(filename)
③ 내용형식(contents type) ctype이 php일 때에 php 문서에 포함된 템플릿 변수들
④ ctype이 template인 단순변수의 변수내용부분
compile 실행시간은 사용자가 지정할 수 없으며, 템플릿 툴이 내부적으로만 사용하는 실행시간입니다.
필터명령 실행시간을 제어하는 방법
템플릿변수의 필터명령은 각각 아래와 같이 지정합니다.
단순변수일 때 {&변수명;;필터명령}변수내용{/}
조건변수일 때 {?변수명;;필터명령}경우의수{/}
블록변수일 때 {@변수명;;필터명령}블록내용{/}
파일변수일 때 {#변수명;;필터명령}파일명{/}
실행시간에 대한 언급없이 단순히 필터명령만 지정하는 경우 위 표 <필터명령 실행시간> 의 default 실행시간으로 처리됩니다. 이러한 default 실행시간은 아래의 파일변수 예에서와 같이 다른 시간으로 강제 지정할 수 있습니다.
{#FILE;;
initialize {%
    =*include_once('{::_PATH_TO_TPLS}/filter.php');
    =|initialize_skin();
%}
premacro {%
    =|prefilter_macro();
%}
precompile {%
    ={_SELF};
%}
postcompile {%
    =|postfilter_compile();
%}
preassign {%
    =|prefilter_assign();
%}
postassign {%
    =|postfilter_assign();
%}
}./include.htm{/}
사용자정의 필터함수들은 각 실행시간에 해당 필터함수가 실행되기 전에 미리 정의되어 있어야 합니다.
강제 지정할 수 있는 실행시간은 각 변수별로 다릅니다. 각 변수별로 허용되지 않는 실행시간은 지정할 수 없으며, 지정했을 때 1.2.0 버전에서는 실행하지 않고 무시해버리나 향후 버전에서는 강제로 에러를 출력 후 프로그램을 중지시킬 수도 있으니 주의하기 바랍니다.
위의 예제에서 표기된 {_SELF}는 필터 처리할 때 사용되는 미리정의된 템플릿변수로 하위템플릿 파일인 include.htm의 내용을 가지고 있습니다. 이 템플릿 변수에 대한 자세한 정보는 "6.2.미리정의된 템플릿변수"를 참조바랍니다.
필터 FLOW
실행시간 중에 premacro, precompile, compile, postcompile으로 지정되는 필터명령들은 템플릿파일을 컴파일할 때만 수행되며, initialize으로 지정되는 필터명령은 컴파일 유무에 관계없이 define() 함수를 실행하는 초기에 수행되며, preassign, assign, postassign으로 지정되는 필터명령들은 assign() 함수를 실행할 때 수행됩니다.
output으로 지정된 필터명령들은 출력버퍼에 있는 문서를 가지고 최종 HTML 스크립트 문서를 생성할 때 수행됩니다.
< 필터 FLOW >
필터명령 구문 형식
지정할 수 있는 필터명령에는 필터상수, php명령, 전처리명령, 사용자정의 필터함수 및 내장 필터함수가 있습니다. 각각의 필터명령은 아래와 같은 표에 의해 지정됩니다.
< 필터명령 구문 형식 >
종 류 구문 형식
필터상수 {@변수명;;필터상수}내용{/}
php명령 {@변수명;;=php명령}내용{/}
전처리명령 {@변수명;;=*전처리명령}내용{/}
사용자정의 필터함수 {@변수명;;=|사용자정의 필터함수}내용{/}
내장 필터함수 {@변수명;;=>내장필터함수}내용{/}*
{@변수명;;=)내장필터함수}내용{/}
* [주의] - 2006.10.26

웹에디터에서 템플릿 문서를 작성할 때 내장 필터함수를 의미하는 "=>"가 제대로 입력되지 않는 문제가 발생하였습니다. 즉, 꺽은괄호(>)를 태그로 인식하여 "&gt;"로 저장되어 필터처리가 원하는대로 되지 않습니다. 따라서 1.2.0의 패치버전(또는 다음버전)에서 꺽은괄호(>) 대신에 둥근괄호와 같은 다른 기호를 사용하려고 합니다. 예를들어 블록변수에서의 내장 필터함수의 구문형식을 현재와 수정안을 비교하여 살펴보면 아래와 같습니다.

현재 : {@변수명;;=>내장필터함수}내용{/}
수정(안) : {@변수명;;=)내장필터함수}내용{/}
허용필터명령 지정하기
허용필터명령을 지정할 수 있는 방법은 아래와 같이 세가지입니다.
① 생성자의 네번째 인자로 새롭게 추가된 필터옵션의 allow_filter 키를 통해서
② define() 함수의 세번째 인자인 옵션의 allow_filter 키를 통해서
③ 파일변수(인클루드문)의 변수옵션 allow_filter 키를 통해서
생성자에서 지정된 허용필터명령은 모든 템플릿문서에 적용됩니다.
[code php;gutter:false] $tpl = new hTemplate(디렉토리정보, 캐시옵션, 컴파일옵션, array( 'allow_filter' => 'func_a, func_c, func_d, func_e, =' ) ); [/code]
'=' 문자를 지정하면 php명령과 전처리명령을 사용할 수 있습니다. '=' 문자를 제외한 func_a, func_c, func_d, func_e는 허용되는 사용자정의 필터함수를 의미합니다. 필터상수와 내장필터함수는 아무런 제한없이 모든 템플릿문서에서 사용할 수 있습니다.
특별히 허용필터명령을 지정하지 않으면 모든 필터명령(필터상수, php명령, 전처리명령, 사용자정의 필터함수 및 내장필터함수)을 사용할 수 있습니다.
define() 함수로 지정된 허용필터명령은 해당 define()에 지정된 템플릿 파일에만 적용됩니다. 또한 생성자에서 지정된 허용필터명령이 있을 때는 생성자에서 지정된 허용필터명령 중에서만 지정할 수 있습니다. 생성자에서 지정하지 않은 허용필터명령을 define() 함수에서 지정하더라도 무시됩니다.
[code php;gutter:false] $tpl = new hTemplate(디렉토리정보, 캐시옵션, 컴파일옵션, array( 'allow_filter' => 'func_a, func_c, func_d, func_e, =' ) ); $tpl->define('main', 'filter.htm', array( 'allow_filter' => 'func_a, func_b, func_e, func_f' ) ); [/code]
템플릿 main(템플릿파일 filter.htm)에서는 사용자정의 필터함수 func_a, func_e만 허용되며 사용자정의 필터함수 func_b, func_f와 php명령, 전처리명령은 허용되지 않습니다. 필터상수와 내장필터함수는 역시 제한없이 사용할 수 있습니다.
마지막으로 파일변수(인클루드문)에서의 허용필터명령에 대하여 살펴보겠습니다.
파일변수에서 지정된 허용필터명령은 파일변수에서 지정된 파일에만 적용됩니다. 또한 현재 템플릿 문서가 생성자 또는 define() 함수로 허용필터명령이 지정된 경우에는 지정된 허용필터명령 중에서만 지정할 수 있습니다.
위 define() 함수로 지정된 허용필터명령의 예에 있는 php 스크립트에서 사용하는 템플릿 문서 filter.htm의 내용이 아래와 같은 경우를 살펴보겠습니다.
[code html;gutter:false] <!-- template file : filter.htm -->{#SAMPLE;allow_filter=func_b, func_c, func_e, =; =|func_a(); =|func_b(); =|func_c(); =|func_d(); =|func_e(); ="[[["."{_SELF}"."]]]"; }./include.htm{/} [/code]
파일변수 SAMPLE 내에서 허용되는 사용자정의 필터함수는 func_e뿐입니다. 왜냐하면 템플릿파일 filter.htm은 define() 함수에 의해 사용자정의 필터함수 func_a, func_e만 허용되었는데 파일변수 SAMPLE에서는 이 중에 func_e만 일치하고 나머지는 define() 함수에 의해 허용되지 않는 필터함수, php명령, 초기화명령이기 때문입니다. 따라서 파일변수 SAMPLE에서 지정한 많은 필터명령중에 다섯번째 필터명령인 =|func_e();만 정상적으로 수행하고 나머지는 무시해 버립니다.
파일변수 SAMPLE에서 지정된 템플릿파일 include.htm 내에서 또 다른 파일변수가 내포되어 있을 경우에 내포된 파일변수에서는 파일변수 SAMPLE에서 허용되는 func_e 함수만 필터명령으로 사용할 수 있습니다.
이와같이 파일변수가 중첩되었을 때는 허용필터명령이 하위 파일변수로 연속적으로 전달되어 허용필터명령을 제한하게 됩니다.
허용필터명령에 와일드카드 사용하기
허용필터명령을 지정할 때 아래와 같은 세가지 와일드카드 문자를 통하여 여러개의 필터명령을 한번에 지정할 수 있습니다.
① The asterisk(*) represents a whole word or a group of characters.
② The question mark(?) represents a single character.
③ The exclamation mark(!) is a character to deny filter functions.
* 문자는 해당 문자가 없거나 하나 이상의 문자(anything or nothing) 대신에 사용될 수 있습니다. 예를 들어 func_*는 func_a, func_b, func_aaa를 모두 나타내며 * 문자 위치에 아무 문자도 없는 func_으로도 나타낼 수 있습니다.
? 문자는 임의의 한 문자(any single character)를 대표해서 나타내며, ?는 a 또는 b 또는 6과도 일치합니다. 그러나 * 문자와는 달리 반드시 하나의 문자가 있어야 합니다. 예를 들어 func_?는 func_a, func_b와는 일치하지만 func_와는 일치하지 않습니다.
! 문자는 지정된 필터명령을 허용하지 않을 때 사용하는 논리적 부정의 의미를 가진 문자입니다. !가 없으면 허용필터명령(allow filter)이 되는 것이고, !가 앞에 있으면 불허필터명령(deny filter)이 되는 것입니다. 만약 func_*에 해당하는 필터명령들을 허용하지 않으려면 !func_*와 같이 맨 앞에 ! 문자를 덧붙이기만 하면 됩니다.
허용필터명령에 일치하지 않는 필터함수 처리
아래와 같이 허용필터명령을 지정하는 4가지 예에서 필터함수명이 일치하지않는 필터함수를 어떻게 처리하는지 살펴보겠습니다.
① {#FILE;allow_filter=func_a, func_b, func_c}./test.htm{/}
② {#FILE;allow_filter=!func_a, !func_b, !func_c}./test.htm{/}
③ {#FILE;allow_filter=func_a, !func_b, func_c}./test.htm{/}
④ {#FILE;allow_filter=func_a, func_b, !func_c}./test.htm{/}
첫번째 예에서는 지정된 func_a, func_b, func_c는 모두 허용필터함수들이며, 두번째 예에서 지정된 func_a, func_b, func_c는 모두 불허필터함수들이며, 세번째와 네번째는 허용필터함수와 불허필터함수가 혼재되어 있으며 차이점은 마지막으로 지정된 필터함수가 허용필터함수냐 불허필터함수냐는 것입니다.
지정된 필터명령과 일치하지 않는 func_d라는 함수가 있다면 각 경우에 func_d 함수는 어떻게 처리될까요? 결론부터 말씀드리자면 첫번째와 세번째 예에서는 실행되지 않고 두번째와 네번째 예에서는 실행됩니다.
실행하느냐 하지않느냐의 기준이 되는 것은 마지막으로 지정된 필터명령이 허용필터명령이냐 불허필터명령이냐 하는 것입니다. 마지막 필터명령이 허용필터명령이면 일치하지 않는 필터명령들은 불허필터명령이 되는 것이고 아니면 허용필터명령이 되는 것입니다.
세번째와 네번째 예는 아래와 같이 작성하여도 같은 결과를 얻을 수 있습니다.
③ {#FILE;allow_filter=func_a, func_c}./test.htm{/}
④ {#FILE;allow_filter=!func_c}./test.htm{/}

Posted by 방글24
phpsource/템플릿2006. 8. 1. 09:31
written: Sep 20 2006
템플릿 변수값을 출력버퍼에 저장하기
output(변수명)
이 함수는 템플릿 변수에 저장되어 있는 HTML 스크립트를 템플릿출력버퍼에 저장하는 기능을 담당합니다.
[code php;gutter:false] $tpl->assign('MAIN', 'main'); $tpl->output('MAIN'); [/code]
위와 같은 경우에 output() 함수는 템플릿 변수 MAIN의 값을 출력버퍼에 저장합니다. 출력버퍼에 저장된 HTML 스크립트는 register_shutdown_function() 함수로 지정된 콜백함수가 실행될 때 브라우저로 전송됩니다.
HTML 스크립트를 출력버퍼에 저장하기
output(HTML스크립트)
output() 함수에 HTML 스크립트를 직접 지정하여 출력버퍼에 그 값을 저장할 수 있습니다.
[code php;gutter:false] $tpl->output('<p>HTML스크립트</p>'); [/code]
위와 같이 output() 함수를 이용하여 HTML 스크립트를 직접 출력버퍼에 저장할 수 있습니다. 단, 기존에 디버깅을 위해 사용되던 예약어인 '-variable', '-template', '-cache'와 블록변수명으로 사용된 단어들은 지정할 수 없습니다.
output() 함수에서 지정된 HTML 스크립트는 후키템플릿의 자체 출력버퍼(템플릿출력버퍼)를 이용하며, 템플릿출력버퍼에 저장된 HTML 스크립트는 프로그램이 종료될 때 브라우저로 전송됩니다. 또한 템플릿 객체 생성후에 print 또는 echo 함수를 이용하여 출력된 HTML 스크립트들도 모두 자체 출력버퍼에 저장된 후 HTML 스크립트보다 나중에 브라우저로 전송됩니다.
따라서 get_assigned() 함수에서 획득한 HTML 스크립트를 순서대로 브라우저로 전송하려면 print 또는 echo 함수를 이용하면 안되며, 반드시 output()함수를 이용하시기 바랍니다.
[code php;gutter:false] $tpl->output($tpl->get_assigned('MAIN')); [/code]
output() 함수를 이용한 디버깅
아래와 같이 output() 함수의 배열인수를 통해 "-variable", "-template", "-cache"를 지정하면 템플릿 변수 정보, 템플릿 구조 정보, 템플릿 캐시 정보를 얻을 수 있습니다. 수집된 정보들은 HTML 스크립트와 마찬가지로 출력버퍼에 저장되며, 프로그램이 종료된 후 브라우저로 전송합니다.
[code php;gutter:false] $tpl->output( array( '-variable', '-template', '-cache' ) ); [/code]
-variable
현재까지 할당되어 있는 템플릿변수에 대한 정보를 수집합니다.
-template
현재까지 템플릿파일로부터 읽고 파싱된 템플릿 구조에 대한 정보를 수집합니다.
-cache
1.2.0 버전부터 제공되며, 캐시관련 정보를 수집합니다.
만약 디버깅 정보 전부가 아닌 일부 템플릿 변수(또는 템플릿 구조 정보, 캐시 관련 정보)에 대하여만 보고 싶다면 아래와 같이 보고싶은 정보 항목을 명시적으로 지정하면 됩니다.
[code php;gutter:false] $tpl->output( array( '-variable PAGEVIEWS HEAD_TITLE COUNTER', '-template MAIN', '-cache DOCUMENT' ) ); [/code]
이 기능에 대한 좀 더 자세한 정보는 "2.2.템플릿 변수 정보", "2.3.템플릿 구조 정보", "2.4.템플릿 캐시 정보"를 참조바랍니다.
헤더태그 내용의 출력 순서
헤더 이전 및 헤더에 포함된 태그의 출력순서는 아래와 같습니다.
[code html;gutter:false] <!doctype html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=euc-kr"> <meta name="Generator">와 같은 메타 태그 기타 헤더 태그 </head> <body .....> [/code]
기타 헤더 태그 내용의 출력순서는 output() 함수로 처리한 순서대로 출력버퍼에 저장되며, 동일한 태그가 중복되어 나타나는 경우에는 첫번째 처리한 태그가 출력됩니다.
INCLUDE 파일이나 get_assigned() 함수로 획득한 템플릿 스크립트(서브 템플릿 스크립트)에 포함된 헤더태그 내용은 이를 포함하고 있는 메인 템플릿 파일(메인 템플릿 스크립트)에 포함된 헤더태그 내용 뒤에 추가됩니다. 한 파일 내에 포함된 서브 템플릿 스크립트가 여러 개 있을 때는 위쪽에 있는 서브 템플릿 스크립트부터 출력버퍼에 저장됩니다. 헤더태그 내와 바디태그 내 모두에 서브 템플릿 스크립트가 있을 때는 헤더태그 내에 있는 서브 템플릿 스크립트부터 출력버퍼에 저장됩니다.

Posted by 방글24
phpsource/템플릿2003. 4. 30. 09:37
written: Jan 28 2002
last modified: Apr 04 2003
템플릿 파일 기본 디렉토리(template roots)
$tpl = new hTemplate(path-to-templates)
객체 생성할 때 생성자에는 템플릿이 저장되어 있는 디렉토리를 지정하여 줍니다. 생략하면 현 PHP 문서의 디렉토리에 템플릿이 있는 것으로 간주됩니다.
템플릿 파일이 저장된 기본 디렉토리는 아래의 예와 같이 생성자의 첫 번재 인수를 통해 지정할 수 있습니다.
[code php;gutter:false] $tpl = new hTemplate('./templates'); [/code]
템플릿 파일 기본 디렉토리의 다중화(multi template roots)
위와 같이 단 하나의 기본 디렉토리를 지정할 수도 있습니다만 1.0.0 버전부터는 배열을 이용하여 하나 이상의 기본 기렉토리를 동시에 설정할 수도 있습니다.
[code php;gutter:false] $tpl = new hTemplate ( array( 'templates', 'templates/sub', '../up/templates' ) ); [/code]
기본 디렉토리가 여러 개 지정되었을 때는 먼저 지정된 디렉토리부터 템플릿 파일을 찾게 됩니다. 즉, 위의 예에서는 먼저 "templates"에서 템플릿 파일을 찾게 되며 만약 이 디렉토리에 원하는 템플릿 파일이 없으면 "templates/sub" 디렉토리에서 찾게 되며 이 디렉토리에도 원하는 템플릿 파일이 없으면 마지막으로 "../up/templates" 디렉토리에서 템플릿 파일을 찾게 됩니다. 이곳에서 조차 원하는 템플릿 파일을 찾지 못한다면 에러가 발생하지요.

Posted by 방글24
phpsource/템플릿2002. 1. 28. 12:47
written: Jan 28 2002
last modified: Sep 20 2006
간단한 구조의 웹문서에서는 템플릿을 사용할 필요가 거의 없을 것입니다. 이러한 경우는 보통 우리가 많이 사용하는 방법인 HTML 문서 내에 PHP 코드를 삽입하여 작성하게 되면 훨씬 빠르고 손쉽게 문서를 작성할 수 있을 것입니다.
문제는 웹사이트의 내용이 점점 다양해지고 규모가 커지게 되면 PHP 코드 삽입 방식으로는 개발 속도와 문서 관리에 있어 금방 한계에 부딪치게 된다는 것입니다. 결국 현재 PHP의 기술 수준으로 볼 때 템플릿툴을 이용하지 않고 복잡한 웹사이트를 개발한다는 것은 거의 시간 낭비가 될 것입니다. (물론 PHP 언어를 위해 작성된 그래픽 웹에디터도 있는 것 같으니 관심있으면 한번 찾아보시길 바랍니다.)
PHP 코드와 HTML의 분리
템플릿툴을 이용하면 PHP 코드에서 HTML을 완전히(?) 분리할 수 있습니다. 이와 같이 HTML을 PHP 코드와 분리하게 되면 웹사이트 개발 속도를 획기적으로 개선시킬 수 있게 됩니다. 양쪽 요소를 별개로 관리 개발할 수 있으며 최소한의 인터페이스만 서로 조정해 주면 되지요. 즉, 템플릿은 웹디자이너들이 담당하여 멋들어지게 만들 것이며, PHP 코드는 웹프로그래머들이 모든 능력을 총동원하여 강력하게 작성할 것이기 때문이지요.
웹디자이너와 PHP 프로그래머 사이에 유일한 통로수단이 바로 템플릿 변수이지요. 다른 것은 서로 전혀 관계없습니다. 앞장에서 설명한 달력을 가지고 이 관계를 설명해 보지요. 아래는 최종적으로 얻어야 할 웹페이지인 달력입니다. 현재는 2001년 12월 달력이 나타나 있지만 이것을 해가 바뀌고 달이 바뀌면 그 내용 역시 바뀌게 될 것입니다.
2001년 12월
             1 
 2   3    4    5    6    7    8 
 9  10   11   12   13   14   15 
16  17   18   19   20   21   22 
23  24   25   26   27   28   29 
30  31            
위와 같은 문서에서 웹디자이너가 담당해야 할 요소는 아래와 같이 달력 디자인 및 정적 데이터들일 것입니다.
{YEAR}년 {MONTH}월
{A1} {A2} {A3} {A4} {A5} {A6} {A7}
{B1} {B2} {B3} {B4} {B5} {B6} {B7}
{C1} {C2} {C3} {C4} {C5} {C6} {C7}
{D1} {D2} {D3} {D4} {D5} {D6} {D7}
{E1} {E2} {E3} {E4} {E5} {E6} {E7}
{F1} {F2} {F3} {F4} {F5} {F6} {F7}
디자인된 화면을 보니 동적으로 바뀌어야 할 데이터들이 모두 템플릿 변수 {A1}, {A2}, ...... , {F7}로 표시되어 있는 것을 알 수 있습니다. 이렇게 하는 것으로 디자이너가 할 일은 다 한 것입니다. 달력을 더 멋있게 만들고 안만들고는 웹디자이너 맘이지요. 아님 사장 맘인가?
이제 남은 것은 PHP 프로그래머가 년도와 월에 맞게 적절한 알고리즘을 이용하여 각 템플릿 변수에 값을 할당하는 것이겠지요. 알고리즘의 성능을 개선하는 것은 프로그래머가 알아서 할 일이며 디자이너와는 전혀 관계가 없지요.
{YEAR} <- "2001"
{MONTH} <- "12"
{A1} <- ""
{A2} <- ""
{A3} <- ""
{A4} <- ""
{A5} <- ""
{A6} <- ""
{A7} <- "1"
{B1} <- "2"

.
.
.

{F1} <- "30"
{F2} <- "31"
{F3} <- ""
{F4} <- ""
{F5} <- ""
{F6} <- ""
{F7} <- ""
결국 HTML과 PHP 코드를 분리하게 됨으로 얻은 이점은 디자이너와 프로그래머가 서로의 영역에서 그 능력을 최대로 발휘하면서 웹사이트의 디자인과 성능을 향상시킬 수 있다는 것이지요. 간단한 웹사이트에서야 한 사람이 이 모든 일을 해야 하니까 별의미가 없다고 생각할 지 모르지만 한 사람이 하더라도 일의 성격을 구분하여 작업할 수 있다는 것만으로도 많은 이득을 얻을 수 있습니다.
일정한 틀을 가지고 반복 사용되는 부분
보통 하나의 웹사이트에서 반복 사용되는 부분을 처리하는데 프레임 태그를 많이 사용합니다. 그러나 요즈음 대부분의 웹사이트에서는 반복되는 부분이 있음에도 불구하여 프레임을 거의 사용하지 않지요.
아래와 같은 예의 홈페이지를 살펴보면 하나의 페이지가 크게 4 구역으로 나누어져 있는 것을 알 수 있습니다. 상단에 위치한 구역에는 베너 및 주 메뉴가 있고, 좌측 구역에는 서브 메뉴가 있고, 중앙 구역은 메인 화면이 있고, 하단 구역에는 관리자 이름을 표시하는 글들이 있습니다.
< 홈페이지의 구성 >
이 중에 상단과 하단 구역은 모든 페이지에서 공유하는 구역이고 좌측 구역은 몇몇 관련 페이지들이 공유하는 구역입니다. 중앙 구역만이 유일하게 모든 페이지마다 다른 내용을 보여주고 있지요. 결국 이와 같은 경우에 공유되는 각 구역을 별도의 템플릿으로 작성해 놓는다면 다른 페이지에서 그 부분을 다시 작성하지 않더라도 템플릿으로 작성해 놓은 것을 읽어 들이는 것만으로도 하나의 페이지를 만들 수 있습니다. 중앙 구역만 각 페이지 마다 새로 작성하면 되는 것이지요.
[code php;gutter:false] <? include_once("class.hTemplate.php"); $tpl = new hTemplate("./templates"); $tpl->define( array( 'top' => 'top.htm', // 상단 구역에 대한 템플릿 'left' => 'left.htm', // 좌측 구역에 대한 템플릿 'center' => 'center.htm', // 중앙 구역에 대한 템플릿 'bottom' => 'bottom.htm' // 하단 구역에 대한 템플릿 ) ); . . . ?> [/code]
< 템플릿을 이용한 홈페이지 구성 >
이와같이 공유하는 구역에 대한 것은 템플릿을 이용하여 공유하게 되면 웹사이트 전체의 코드양을 상당수 줄일 수 있을 것입니다.

'phpsource > 템플릿' 카테고리의 다른 글

{후키템플릿}3.7.output()  (0) 2006.08.01
{후키템플릿}4.1.템플릿 파일 경로  (0) 2003.04.30
{후키템플릿}0.4.라이선스(License)  (0) 2002.01.28
{후키템플릿}7.4.URL 리디렉션  (0) 2002.01.28
FastTemplate 1.1.0  (0) 2000.08.06
Posted by 방글24
phpsource/템플릿2002. 1. 28. 11:50
written: Sep 20 2006
hwooky's Template(hTemplate;hT) is licensed using LGPL. Copyright (c) 2005-2006 Wookyung Hwang(hwooky@phpclass.com). All rights reserved.
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

-GNU LESSER GENERAL PUBLIC LICENSE (LGPL)

Address Bug Reports or Comments on THIS LIBRARY ONLY to Wookyung Hwang, hwooky@phpclass.com.
The latest version of this class should be available from the following locations: http://www.phpclass.com(korean only)

For more info about hwooky's Template(hTemplate;hT), visit http://www.phpclass.com(korean only)
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999

Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL. It also counts
 as the successor of the GNU Library Public License, version 2, hence
 the version number 2.1.]


Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.

This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below.

When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.

To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it.

For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.

We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.

To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.

Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.

Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.

When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.

We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.

For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.

In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.

Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.

The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run.


TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you".

A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables.

The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".)

"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.

Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.

1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library.

You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.

2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:


a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful.
(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)

These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library.

In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.

3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices.

Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy.

This option is useful when you wish to copy part of the code of the Library into a program that is not a library.

4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange.

If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.

5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.

However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.

When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law.

If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.)

Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.

6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications.

You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:


a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.

It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.

7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:


a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.

10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.

11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library.

If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.

This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.

12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.

13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.

14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

NO WARRANTY

15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.


END OF TERMS AND CONDITIONS

Posted by 방글24
phpsource/템플릿2002. 1. 28. 11:19
written: Jan 28 2002
last modified: Sep 20 2006
URL 리디렉션(redirection)
URL 리디렉션의 필요성
사실 개발자가 템플릿을 이용하는 가장 큰 이유라면 당연히 웹디자인 부분과 PHP 코딩 부분을 분리하기 위해서 입니다. 이러한 이유로 템플릿은 웹디자이너가 나모 웹에디터와 같은 위지윅 웹에디터를 이용하여 작성하는데 불편함이 없어야 하며, 아울러 웹에디터에 나타나는 각 부분의 의미가 명확하여야 합니다. 이러한 관점에서 볼 때 현재까지 나와 있는 모든 템플릿툴에서 발견되는 문제라고 하면 템플릿에서 작성된 HTML 소스(자바 스크립트 소스 포함)에 포함된 URL(Uniform Resource Locator)이 PHP로 해석될 때는 설정된 템플릿 경로에 따라 전혀 다르게 표기된다는 것입니다.
이 문제를 해결하기 위해서는 템플릿과 PHP 문서를 동일한 디렉토리에 보관하든가, 아니면 템플릿에 있는 URL을 상대경로가 아닌 절대경로를 이용하든가 등등 해야 할 것입니다. 이것이 현실적으로 곤란하다면 템플릿에 있는 URL을 전부 PHP 문서 위치에 맞게 변경하는 수고를 해야겠지요.
후키템플릿에서는 이 문제를 해결하기 위해 제가 앞서 공개하였던 HTML 파서를 이용하게 되었습니다. define() 함수에 의해 읽어들인 템플릿 파일을 HTML 파서에 의해 태그 단위로 분석한 후 URL이 있는 부분들을 전부 찾아 내어 PHP 문서에 맞게 변경 시켜주게 됩니다.
URL 리디렉션 = 웹문서 리디렉션 + 리소스 리디렉션
나모와 같은 웹에디터를 이용하여 작성된 웹문서(여기서는 템플릿 파일을 의미함)에 포함된 각종 파일이 있는 위치를 PHP 문서의 위치에 맞게 적절히 변경해주는 "URL 자동 변경" 기능을 최초 버전부터 제공하여 왔었습니다만 이 기능이 그림과 같은 리소스를 처리하는데는 적절하였으나 하이퍼링크로 연결된 HTML 문서의 위치를 처리하는데는 문제가 많이 있었습니다.
따라서 1.0.0 버전부터는 그림과 같은 웹문서의 위치 변경과 웹문서가 아닌 나머지 모든 리소스(그림, 동영상 등)의 위치 변경에 대한 기능을 구분하여 제공합니다. 이 문서에서는 하이퍼링크로 연결된 HTML 문서의 위치 변경을 "웹문서 리디렉션", 그림 또는 동영상과 같은 나머지 리소스의 위치 변경을 그냥 "리소스 리디렉션"이라는 용어로 부르겠으니 혼동없기를 바랍니다. 즉, "리소스 리디렉션"이라고 했을 때는 웹문서를 제외한 파일에 대한 리디렉션을 의미합니다. 만약 웹문서를 포함한 모든 리소스에 대한 리디렉션을 지정할 때는 웹문서 또는 리소스라는 접두어없이 "리디렉션" 또는 "URL 리디렉션"이라고 부르겠습니다.
사실 태그의 속성으로 지정되는 각종 URL이 그림, 동영상, 웹문서를 모두 지원하는 경우가 많으므로 양쪽 기능을 설명하는데 있어서 명확히 구분되지 않는 부분도 많이 있을 것입니다.
URL 리디렉션이 적용되는 URL 형식
URL이 절대 경로로 지정되었다면 리디렉션이 필요없을 것입니다. 따라서 "./" 또는 "../"로 시작되는 URL이나 파일명과 쿼리문만으로 구성된 URL일 경우에만 리디렉션 기능이 적용됩니다. 만약 URL이 템플릿 변수로 지정되었다면 이 URL은 PHP 소스에서 자신의 위치에 맞게 정확하게 지정할 것이기 때문에 역시 리디렉션을 하지 않습니다.
URL 리디렉션이 가능한 태그 속성들
아래는 리디렉션 해주는 태그 속성 및 스타일 속성입니다.
태그명     속성명
------ ------
IMG src, lowsrc
EMBED src
INPUT src
FRAME src
IFRAME src
SCRIPT src
BODY background
TABLE background
TR background
TH background
TD background
LINK href
BASE href
A href
Q cite
BLOCKQUOTE cite
INS cite
DEL cite
OBJECT data
FORM action
PARAM value

스타일
------
<태그명 style="background-image:url(URL)">
<STYLE>
@import url(URL);
background-image: url(URL);
background: #fcf url(URL) 50%;
list-style-image: url(URL);
list-style: lower-roman inside url(URL);
</STYLE>
1.0.0 이전 버전에서는 <PARAM> 태그에 포함된 URL에 대한 리디렉션 기능을 제공하지 못했습니다.
1.0.0 버전부터는 <PARAM> 태그의 'value' 속성이 URL일 경우에도 리디렉션 기능을 수행하도록 개선하였습니다.
혹시 리디렉션이 필요한 태그가 더 있다면 게시판을 통해 알려주시기 바랍니다.
자바 스크립트에 포함된 URL 리디렉션
자바 스크립트에 있는 URL의 리디렉션까지 지원한다는 것은 그 구현이 무척이나 어려운 것 같습니다. 그래서 완벽한 지원이라기 보다는 한가지 약속을 통하여 이를 해결하고자 합니다.
자바 스크립트에서 URL을 리디렉션하고 싶은 경로가 있다면 이 부분은 아래와 같이 별도로 관리하여 주시기 바랍니다.
[code html;gutter:false] <SCRIPT language="javascript" tpl="URL"> <!-- OpenMail = "./../mail.php"; OpenHelp = "./../help_search.php"; //--> </SCRIPT> <SCRIPT language="javascript"> <!-- function openMail(to) { pos = ',left='+(screen.width-240)/2+',top='+(screen.height-240)/2; popup = window.open('', 'mail_window', 'scrollbars=no,width=240,height=240' + pos); popup.location.href = OpenMail + '?to=' + to; popup.focus(); } //--> </SCRIPT> <INPUT type=button value='도움말' name=help onClick='openWindow(500, 400, OpenHelp)'> [/code]
OpenMail과 OpenHelp가 바로 리디렉션하고 싶은 URL이 저장되어 있는 자바 스크립트 변수입니다. 이 예처럼 URL을 변경하고 싶은 자바 스크립트 변수명들은 한 곳에 묶어서 따로(다른 SCRIPT 문장과 분리하여) 관리하세요. 이 때 태그 SCRIPT의 사용자 정의 속성 'tpl'을 'URL'라고 지정하여 주셔야 합니다. 그리고 나서 다른 자바 스크립트 문장에서는 이 변수를 이용하시면 됩니다. 이것만 지켜주신다면 자바스크립트에 포함된 URL을 자동 변경하는데 별 문제가 없을 것입니다.
버전 0.0.2 이전 버전에서는 사용자 정의 속성 'tpl' 대신에 'name'를 사용하였으나 이 속성명 'name'은 실제로 태그에서 사용하는 속성이다보니 충돌이 일어나는 경우가 발생하여 0.0.2 버전부터는 'name' 속성을 지원하지 않습니다.
< URL 자동 변경을 위한 속성 지정 <
버전 속성명 속성값 향후 호환성
0.0.1 name URL4TPL 호환성 없음
0.0.2 name URL4TPL "
tpl URL 호환성 있음
'7.7.복수 템플릿 파일의 용법'에서 자세히 언급하겠지만 속성 'tpl'에 설정할 수 있는 또 다른 값 'TMP'가 있습니다. 'TMP' 용법에 대한 자세한 것은 뒷 장 '7.7.복수 템플릿파일의 용법'을 참조바랍니다. 만약 'URL', 'TMP' 값 모두를 설정하려면 아래와 같이 콤마로 구분하여 속성값을 지정하면 됩니다. 순서는 관계없습니다.
[code html;gutter:false] <SCRIPT language="javascript" tpl="URL,TMP"> <!-- OpenMail = "./../mail.php"; OpenHelp = "./../help_search.php"; //--> </SCRIPT> [/code]
이제는 URL 리디렉션 문제로 웹디자이너와 프로그래머가 만날 일이 별로 없을 것입니다.
내장 필터함수 url()을 이용한 URL 리디렉션
1.2.0 버전부터는 자바 스크립트에 포함된 URL의 리디렉션을 tpl 속성을 사용하지 않더라도 내장 필터함수인 url() 함수를 이용하여 아래와 같이 쉽게 구현할 수 있습니다.
[code html;gutter:false] <SCRIPT language="javascript"> <!-- function openMail(to) { pos = ',left='+(screen.width-240)/2+',top='+(screen.height-240)/2; popup = window.open('', 'mail_window', 'scrollbars=no,width=240,height=240' + pos); popup.location.href = "{=>url('./../mail.php')}" + '?to=' + to; popup.focus(); } //--> </SCRIPT> <INPUT type=button value='도움말' name=help onClick='openWindow(500, 400, "{=>url('./../help_search.php')}")'> [/code]
내장 필터함수를 이용하는 방법에 대하여는 '8.7.내장 필터함수'를 참조바랍니다.
자바 스크립트 이벤트 핸들러에 의해 실행되는 함수
[code html;gutter:false] <A href="index.html" onMouseOver="test('arg1', 'arg2', 'images/test.gif', true);"> test </A> [/code]
위의 예와 같이 각종 태그 내에 지정된 이벤트 핸들러에 의해 실행되는 함수로 전달되는 인수 중에 있는 URL을 리디렉션해 줍니다.
해당되는 이벤트 핸들러에는 'onAbort', 'onBlur', 'onChange', 'onClick', 'onError', 'onFocus', 'onLoad', 'onMouseOut', 'onMouseOver', 'onReset', 'onSelect', 'onSubmit', 'onUnload'가 있습니다.
이 기능은 1.0.0 버전부터 지원됩니다.
URL 리디렉션에서의 문제점
PHP 스크립트로 HTML 태그를 분석하는 일은 많은 시간이 소요되는 일입니다. 그러나 뒷장에서 언급하고 있는 '템플릿 캐시'을 이용하면 URL 리디렉션을 할 때와 하지 않을 때의 차이가 거의 없습니다. 템플릿의 변경을 즉시 반영하여 페이지를 생성하기 때문에 여러분은 캐시를 사용하는지 하지 않는지 조차 전혀 눈치챌 수 없습니다. 이 기술은 이전에 공개했던 유닛테이블에서 써 먹던 것이었는데 여기서 다시 써 먹게 되네요.

Posted by 방글24
phpsource/템플릿2000. 8. 6. 19:56
FastTemplate 1.1.0
FastTemplate-1.1.0은 FastTemplate 클래스의 최종 버전으로 더 이상 버전업은 없습니다. 원본을 확인하시려면 이 곳(www.thewebmasters.net)을 클릭하시던지 아니면 아래 복사본을 참조하세요.

Posted by 방글24
phpsource/템플릿2000. 8. 6. 16:48
비교항목
  • 용도
  • 수행속도
  • 소스코드 크기
  • 템플릿 파일 형식
  • 공개여부
  • A/S 수준
이 외에도 비교할 수 있는 항목으로는 가독성, 코드 작성의 편의성, 각 툴의 장단점 등이 있겠으나 이러한 항목은 개인에 따라 평가 결과가 전혀 다를 수 있기 때문에 여기서는 비교하지 않았으며, 필요하면 여러분이 직접 비교해 보고 "후키라이브러리 Q/A" 게시판에 의견을 주시기 바랍니다. 그러면 제가 나중에 그것을 기반으로 하여 정리하여 보겠습니다. VH layout은 공개용과 상용의 두 가지 버전이 있습니다. 여기서 비교하고 있는 버전은 공개용입니다.(제가 돈주고 사면서까지 실험할 수 없는 고로 이해하시길...)
수행속도
수행속도는 서버 상에서 스크립트가 시작되는 시간부터 종료되는 시간까지 소요되는 시간을 초단위로 나타내었습니다. 이 때 사용되는 벤치마킹용 함수는 FastTemplate 내에 포함된 클래스의 메소드 utime()을 이용했습니다. 아래에 각 툴 예제소스에 포함된 벤치마킹 소스를 나타내었습니다.
[code php;gutter:false] <?php function utime () { // Benchmarking $time = explode( " ", microtime()); $usec = (double)$time[0]; $sec = (double)$time[1]; return $sec + $usec; } $start = utime(); // 시작시간 // // 이 부분에 각 페이지툴의 예제 소스코드가 있습니다. // $end = utime(); // 종료시간 $runtime = $end - $start; // 소요시간 echo "Completed in $runtime seconds\n"; ?> [/code]
수행속도에 나타난 수치는 각 툴 사이의 상대적인 비교 값으로만 참조하시기 바라며, 또 한가지 주의할 것은 수행속도가 서버 상에서의 비교한 수치이기 때문에 실제 인터넷상에서 느끼는 속도하고는 전혀 다르다는 것을 이해해 주시기 바랍니다. 즉, 서버의 수행속도보다 네트워크의 전송속도가 훨씬 느린 게 현실이며, 최종 방문자가 느끼는 속도는 서버의 속도보다는 네트워크의 전송속도에 의해 거의 결정된다고 생각됩니다.
수행속도 측정은 두 가지 환경에서 실험했습니다. MySQL과 Apache는 두 환경에서 동일하고 PHP버전만 다릅니다.
  • 첫 번째 환경 - PHP 3.0.14
  • 두 번째 환경 - PHP 4.0.4
소스코드 크기
여기서 표기된 소스코드 크기는 페이지툴만 포함시킨 것으로, 사용자가 작성해야 하는 템플릿 파일 또는 PHP 코드는 제외시켰습니다. 따라서 페이지툴에 따라 템플릿 파일 또는 PHP 코드의 크기가 차이가 있을 수 있음을 염두에 두시기 바랍니다.
기타
VH layout 예제를 제외하고 나머지는 전부 제 홈페이지에서 생성되는 HTML 태그를 모델로 하여 예제를 작성하였습니다. VH layout은 함수로 복잡한 레이아웃 구조를 표현하기가 쉽지 않아 제 홈페이지의 HTML 소스 대신에 VH layout에서 받은 예제를 거의 그대로 하여 예제로 올렸습니다. FastTemplate에는 다이내믹 블록이라는 고급기능도 있으나 이를 사용하지 않고, 단순히 템플릿 변수를 치환하여주는 기능만을 사용하였습니다. 이런 저런 이유로 각 툴에 대한 예제 자체에 저의 편중된 시각이 의식적이든 무의식적이든(고의는 아니지만) 내재되어 있음을 염두에 두시고 아래의 비교 데이터를 참조하시기 바랍니다.
비교 데이터
구분 FastTemplate VH layout UnitTable 0.1.3 UnitTable 0.2.0 HTML
용도 템플릿툴 레이아웃툴 템플릿툴 + 레이아웃툴 -
수행속도(PHP3) 0.161sec 0.527sec 0.816sec 0.330sec 0.010sec
수행속도(PHP4) 0.096sec 0.254sec 0.310sec 0.164sec 0.002sec
소스코드 크기 16KB
(752라인)
23KB
(959라인)
25KB
(1030라인)
22KB
(770라인)
-
템플릿 파일 형식 HTML 태그
(file())
- 텍스트파일
(fopen())
텍스트파일
(file())
-
공개여부 공개용 공개용/상용 구분 공개용 -
A/S 수준? 책임감 있는 웹사이트라고 생각함 상용까지 제공하고 있으니 Upgrade가 잘 될 거라고 추측됨 전 아마추어예요. 따라서 A/S 보장 못해-앵 -
유닛테이블 0.1.3 對 0.2.0
위에서 비교한 유닛테이블의 수행속도는 MySQL용 미니디비 0.2.2를 기본으로 사용하였을 경우의 속도를 나타냅니다. 이 때의 유닛테이블 실행속도를 보면, 0.2.0버전이 0.1.3 버전에 비해 1.9배(PHP4)~2.5배(PHP3)가량 빠르게 향상되었습니다.

Posted by 방글24
phpsource/템플릿2000. 8. 6. 16:42
구성
< 유닛테이블을 DB Layer에 접속 >
유닛테이블 통일버전 0.1.3에서는 PHPLIB 및 MiniDB에 있는 각 데이터베이스 관련 클래스 파일을 동일한 방법으로 사용합니다. 따라서 각 DB Layer를 구성하는 클래스 파일을 인클루드 하는 방법만 익히시면 됩니다. 인클루드 부분을 제외한 나머지 모든 인터페이스는 이전 버전과 동일합니다.
각 DB Layer별로 지원되는 데이터베이스 및 클래스 파일
데이터베이스 MiniDB 0.1.1 PHPLIB 7.2
MSQL class.msql.php db_msql.php
MSSQL class.mssql.php db_mssql.php
MySQL class.mysql.php db_mysql.php
Oracle(OCI) class.oci8.php db_oci8.php
Oracle(ORA) class.oracle.php db_oracle.php
ODBC X db_odbc.php
PostgreSQL class.pgsql.php db_pgsql.php
SyBASE class.sybase.php db_sybase.php
PHPLIB의 라이브러리를 사용하면서 발생하는 문제는 해당 웹사이트의 게시판을 통해 문제점을 해결하세요. phpCLASS 홈페이지에서는 MiniDB에 대한 질문만 받습니다.
MiniDB를 사용하는 방법
[code php;gutter:false] <?php //====================================== // 객체 생성 부분 //====================================== require("./minidb-0.1.1/class.mysql.php"); require("./class.pageworks.php"); . . . $pw->parseprint($modify); ?> [/code]
위의 예는 MySQL에 대하여 나타내었습니다. 다른 데이터베이스는 상단 표를 참조하여 "class.mysql.php" 부분을 변경하여 주십시오.
PHPLIB를 사용하는 방법
[code php;gutter:false] <?php //====================================== // 객체 생성 부분 //====================================== require("./PHPLIB/db_mysql.php"); require("./class.pageworks.php"); . . . $pw->parseprint($modify); ?> [/code]
위의 예는 MySQL에 대하여 나타내었습니다. 다른 데이터베이스는 상단 표를 참조하여 "db_mysql.php" 부분을 변경하여 주십시오.

'phpsource > 템플릿' 카테고리의 다른 글

FastTemplate 1.1.0  (0) 2000.08.06
{유닛테이블}15.각 툴의 비교  (0) 2000.08.06
{유닛테이블}13.기본 메소드  (0) 2000.08.06
{유닛테이블}12.템플릿상수 & 변수  (0) 2000.08.06
{유닛테이블}11.데이터형식  (0) 2000.08.06
Posted by 방글24