프로그래밍.../Smarty | Posted by 고기킬러 2009. 12. 23. 10:14

Smarty 반복문(FOREACH)

FOREACH (반복문)
----------------

특별히 당신이 오직 한 가지 변수를 통해 반복문을 만들고 싶다면, 그런 당신을 위해 좀
더 쉬운 방법으로 연관배열을 반복시킬 수도 있는데, 이를 보여주는 아래 예제는 Smarty
와 함께 제공하는 디폴트 index.php에서 작동하는 템플릿인데,


{foreach name=outer item=contact from=$contacts}
{foreach key=key item=item from=$contact}
{$smarty.foreach.outer.iteration}. contact {$key}: {$item}
{/foreach}
{foreachelse}
no contacts
{/foreach}


여기서 가능한 속성들로는 다음과 같은 것들이 있어요[역주: 아래의 item, key, from은
PHP에서는 foreach($array as $key=>$item)와 각각 대입된다고 생각하시면 됩니다]

from: 반복의 대상이 되는 배열
item: 배열의 현재 요소를 가리키는 변수의 이름
key: 배열의 현재 키를 가리키는 변수의 이름(선택적)
name: foreach의 이름 (선택적)

그리고 당신이 만일 'name'을 사용한다면 다음과 같이 보다 다양한 foreach 속성들을 추
가할 수도 있으며[역주: first, last, show는 무슨 소리를 하고 있는지 잘 모르겠습니다.
메뉴얼에도 이 부분은 설명한 게 없고요. 실제 예제를 작성해 봐야 알 것 같군요. --;],

name: foreach의 이름
iteration: 현재 반복 횟수
total: 반복할 전체 횟수
first: if it's first iteration
last: if it's last iteration
show: if foreach was shown at all

아래 있는 템플릿은 foreach의 모든 속성들을 출력해 주는 예제랍니다[역주:두번째
foreach 문장에서 $smarty.foreach.outer가 from 속성의 값으로 지정된 것을 주목하
시기 바랍니다. 여기에 contact를 지정한 경우 전혀 다른 출력이 나옵니다].


{foreach name=outer item=contact from=$contacts}
{foreach key=key item=item from=$smarty.foreach.outer}
{$key}: {$item}
{/foreach}
{/foreach}


자, 이제 Smarty에 들여놓은 당신의 발은 어느 정도 충분히 적셔졌을 거에요. 그러나, 아
직 config 파일 변수들이나, built-in 함수들, 커스텀 함수들, 변수 변환자 같은 굵직굵
직한 공부거리가 남아 있답니다. 지금 당장 메뉴얼을 읽으러 가세요[역주: 각종 템플릿
라이브러리 중에서 가장 방대한 양을 자랑하는 메뉴얼입니다. ^^;]. 메일링 리스트에도
가입하시는 것이 좋겠지요. 그럼 앞으로도 Smarty를 즐기시기를!!

출처 : PHP SCHOOL
역자 : 조한석 님 <sizer@systong.co.kr>
SECTIONS: Dynamic Blocks (섹션: 동적 블럭)
------------------------------------------    

Smarty에서 {section} 기능을 사용하면 비교적 간단하게 배열들을 반복해서 출력할 수 있
어요. 여기서 section에는 두가지 속성이 필요로 한답니다. 하나는 name인데 말 그대로
이것은 section의 이름이랍니다[역주: 아래 예제를 보시면 아시겠지만, 이 name 속성은
템플릿 내에서 사용됩니다]. 그리고 또 다른 하나는 loop라는 속성인데, 이 loop는
section에서 몇 번이나 반복할 지 반복횟수를 설명하고 있는 배열의 이름을 가리킨답니
다[역주: 아래 예제에서 "FirstName"과 "LastName"이라는 변수와 함께 지정된 배열의 크
기가 3이므로 3번 반복하게 됩니다.]


--------- index.php --------
<?php
require("Smarty.class.php");
$smarty = new Smarty;
$smarty->assign("FirstName",array("Ned","Bart","Montgomery"));
$smarty->assign("LastName",array("Flanders","Simpson","Burns"));
$smarty->display("index.tpl");
?>

--------- templates/index.tpl --------
{include file="header.tpl" title="Home Page"}
{section name=people loop=$FirstName}
{$smarty.section.people.rownum} {$FirstName[people]} {$LastName[people]}<br>
{sectionelse}
There are no values to loop through.
{/section}
<p>
There were {$smarty.section.people.loop} names in this list.
{include file="footer.tpl"}


여기서 템플릿 내에서 사용된 {$smarty}라는 변수에 대해서 소개할 필요가 있을 것 같네
요. section 내에서 출력되는 변수들을 주목해 보세요. 이처럼 section 내에서 출력할 변
수들은 모두 반드시 섹션 이름으로 참조될 필요가 있음을 잊지 마세요. 이것은 당신이 출
력하고 싶은 값을 배열에서 현재 반복 횟수를 가지고 찾기 위해 필요한 거에요. 또한 내
부 템플릿 변수들을 가지고 현재 반복 중인 section의 총 반복횟수와 현재 반복 횟수 같
은 것도 출력이 가능하답니다. {sectoinelse}도 중요한 건데, 이것은 만일 반복할 배열인
$FirstName이 빈 배열의 경우 대신 출력되는 부분이 된답니다.

그리고 아래 예제에서 사용된 문법처럼 배열의 키들을 가지고 접근할 수도 있어요.


--------- index.php --------
<?php
require("Smarty.class.php");
$smarty = new Smarty;
$smarty->assign(array("ContactInfo" =>
         array(
             array("FirstName" => "Ned","LastName" => "Flanders"),
             array("FirstName" => "Monty","LastName" => "Burns")
             )
));
$smarty->display("index.tpl");
?>


--------- templates/index.tpl --------
{include file="header.tpl" title="Home Page"}
{section name=people loop=$ContactInfo}
{$ContactInfo[people].FirstName}
{$ContactInfo[people].LastName}<br>
{sectionelse}
There are no values to loop through.
{/section}
<p>
There were {$smarty.section.people.loop} names in this list.
{include file="footer.tpl"}


혹은 아래 예제처럼 당신은 복합 중첩 section 문을 시도해볼 수도 있답니다.


--------- index.php --------
<?php
require("Smarty.class.php");
$smarty = new Smarty;
$smarty->assign("FirstName",array("Ned","Bart","Montgomery"));
$smarty->assign("LastName",array("Flanders","Simpson","Burns"));
$smarty->assign("ContactNames",
        array(
         array("email","home","cell"),
         array("email","home"),
         array("email","home","fax")
         ));
$smarty->assign("ContactVals",
        array(
         array("ned@simpsons.com","555-666-7777","555-444-3333"),
         array("bart@simpsons.com","555-111-2222"),
         array("monty@simpsons.com","555-888-9999","555-234-5678"),
         ));

$smarty->display("index.tpl");
?>


--------- templates/index.tpl --------
{include file="header.tpl" title="Home Page"}
{section name=people loop=$FirstName}
{$smarty.section.people.rownum} {$FirstName[people]} {$LastName[people]}<br>
{section name=contacts loop=$ContactNames[people]}
{* for fun, lets bold every other row *}
{if $smarty.section.contacts.rownum is even}<b>{/if}
{$ContactNames[people][contacts]}: {$ContactVals[people][contacts]}<br>
{if $smarty.section.contacts.rownum is even}</b>{/if}
{/section}
<br>
{sectionelse}
There are no values to loop through.
{/section}
<p>
There were {$smarty.section.people.loop} names in this list.
{include file="footer.tpl"}


출처 : PHP SCHOOL
역자 : 조한석 님 <sizer@systong.co.kr>

'프로그래밍... > Smarty' 카테고리의 다른 글

Smarty 한글 매뉴얼  (0) 2009.12.23
Smarty 반복문(FOREACH)  (0) 2009.12.23
Smarty IF/ELSEIF/ELSE  (0) 2009.12.23
Smarty 템플릿 포함하기(INCLUDE)  (0) 2009.12.23
Smarty 변수대입(ASSIGNING VARIABLES)  (0) 2009.12.23
프로그래밍.../Smarty | Posted by 고기킬러 2009. 12. 23. 10:10

Smarty IF/ELSEIF/ELSE

IF/ELSEIF/ELSE
--------------

아래 에제는 매우 직접적인 문법을 보여주고 있을 뿐이랍니다. 메뉴얼에서 좀 더 자세하
게 이 문법에 대해 설명해 주니까 좀 더 알고 싶은 분은 메뉴얼을 참조하도록 하세요.


--------- templates/index.tpl --------
{include file="header.tpl" title="Home Page"}
{if $Name eq ""}
Hello, Noname!<br>
{elseif $Name eq "Ned"}
Hello, Neddy!<br>
{else}
Hello, {$Name}<br>
{/if}

{$FirstName}, {$LastName}<br>
{$Address}, {$Zipcode}
{include file="footer.tpl"}


출처 : PHP SCHOOL
역자 : 조한석 님 <sizer@systong.co.kr>