반복 구문: for 문
기본 구문은 다음과 같습니다:
{for $i = $start to $end step 1}
여기서 $start는 시작값, $end는 종료값, step은 증가 단위를 의미합니다.
$msma->assign('start', 1);
$msma->assign('end', 100);
템플릿 내에서 반복 처리 예시:
<!-- 출력: 1부터 100까지 숫자 출력 -->
{for $i = $start to $end}
{$i}<br />
{/for}
3개씩 줄바꿈:
{for $i = $start to $end}
{$i}
{if $i % 3 == 0}<br />{/if}
{/for}
홀수만 출력 (스텝 2):
{for $i = $start to $end step 2}
{$i}<br />
{/for}
첫 번째와 마지막 항목 강조:
{for $i = $start to $end step 5}
{if $i@first == $i@iteration}
<font color='red'>{$i} </font>
{elseif $i@last == $i@iteration}
<font color='red'>{$i} </font>
{else}
{$i}
{/if}
{/for}
반복 구문: foreach 문
두 가지 문법 방식이 존재합니다:
- Smarty 2 스타일:
{foreach from=$array key=k item=v} - Smarty 3 스타일:
{foreach $array as $k => $v}
데이터베이스에서 상품 목록을 가져와 템플릿에 전달하는 예제:
<?php
header('content-type: text/html; charset=utf-8');
require_once 'libs/Smarty.class.php';
require 'MySmarty.class.php';
$msma = new MySmarty();
$conn = new mysqli('localhost', 'root', 'root', 'boolshop');
$conn->query('set names utf8');
$sql = 'SELECT * FROM goods LIMIT 10';
$res = $conn->query($sql);
$data = [];
while ($row = $res->fetch_assoc()) {
$data[] = $row;
}
$msma->assign('goodslist', $data);
$msma->display('temp12.html');
?>
템플릿에서 데이터 표시:
<table border="1" cellspacing="0" cellpadding="0" height="400">
<tr>
<th>번호</th>
<th>상품 코드</th>
<th>상품명</th>
<th>가격</th>
</tr>
{foreach $goodslist as $k => $v}
{if $v@first || $v@last}
<tr style="background-color:#f69">
<td>{$v.goods_id}</td>
<td>{$v.goods_sn}</td>
<td>{$v.goods_name}</td>
<td>{$v.shop_price}</td>
</tr>
{else}
<tr>
<td>{$v.goods_id}</td>
<td>{$v.goods_sn}</td>
<td>{$v.goods_name}</td>
<td>{$v.shop_price}</td>
</tr>
{/if}
{/foreach}
</table>
반복 구문: section 및 while 문
section은 인덱스 배열에만 사용 가능하며, 다음과 같이 사용됩니다:
{section loop=$array name=index}
{$array[index].key}
{/section}
index는 각 반복에서의 인덱스 값(0, 1, 2 등)을 나타냅니다.
예제: 첫 번째와 마지막 행 색상 변경:
<table border="1" cellspacing="0" cellpadding="0" height="400">
<tr>
<th>번호</th>
<th>상품 코드</th>
<th>상품명</th>
<th>가격</th>
</tr>
{section loop=$goodslist name=i}
{if $smarty.section.i.first || $smarty.section.i.last}
<tr style="background-color:#ccc">
<td>{$goodslist[i].goods_id}</td>
<td>{$goodslist[i].goods_sn}</td>
<td>{$goodslist[i].goods_name}</td>
<td>{$goodslist[i].shop_price}</td>
</tr>
{else}
<tr>
<td>{$goodslist[i].goods_id}</td>
<td>{$goodslist[i].goods_sn}</td>
<td>{$goodslist[i].goods_name}</td>
<td>{$goodslist[i].shop_price}</td>
</tr>
{/if}
{/section}
</table>
while 문 사용 예:
{while $num >= 0}
{$num--}<br />
{/while}
주의: Smarty에서는 ++$i 또는 --$i 형식의 수치 연산을 지원하지 않습니다. 대신 {$i++} 또는 {$i--} 형태로 사용해야 합니다.