Smarty標籤運算,控制結構[if,for,foreach,section,while]

Smarty標籤運算:

在頁面上做簡單的運算[temp5.html]

條件判斷if

循環結構

for

foreach用得比較多,foreach例子從數據庫取出的數據

section功能和foreach類似,沒foreach好理解 不推薦用

while

<?php
/*
smarty html標籤可以運算
if elseif else判斷
for循環
foreach循環
*/
require('../../smarty3/libs/Smarty.class.php');
require('./mysmarty.class.php');
$smarty=new MySmarty();

// 運算
$age=18;
$smarty->assign('age',$age);

// for循環
$start=1;
$end=100;
$smarty->assign('start',$start);
$smarty->assign('end',$end);

// foreach循環
// 連接數據庫
$conn=mysqli_connect('localhost','root','123456','boolshop');
//設置字符集
$sql ='set names utf8';
mysqli_query($conn,$sql);
$sql ='select * from goods limit 5';
$rs=mysqli_query($conn,$sql);
// 取出數組
$goods=array();
while($row=mysqli_fetch_assoc($rs)){
	$goods[]=$row;
}
$smarty->assign('goods',$goods);

$smarty->display('temp5.html');

?>


temp5.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>temp5</title>
</head>

<body>
<!-- 運算 -->
	<h1>{$age}</h1>
	<h1>{$age+60}</h1>
	<h2>{if $age>18}</h2>
	play play
	<h2>{else if $age<18}</h2>
	還不能 play play
	<h2>{else}</h2>
	十八年如何勾勒才顯得從容閒適
	十八年盡心竭力但求隨自己意志
	{/if}
<br/>

	<!-- for循環
	格式:for $i=數字或變量 to 數字或變量 step 隔幾個 -->

	<!-- 1-100打印奇數,隔三個換行;
	奇數可以用步長step 2就是間隔2,-》1 3 5
	$i%3==0打印出第一行是1 3因爲3是整除了,但不應該根據i,而是根據一共有幾個數
	$i@total = (end-start+1)/step 是打印的總個數
	$i@iteration =每次增加至有多少個的變量
	-->
	{for $i=$start to $end step 2}
	{$i} 
	{if $i@iteration%3==0}
	<br/>
	{/if}
	{/for}
	
	<br/>

	{literal}
	<!-- foreach 循環
	格式:foreach $數組名 as $k=>$v[可以自己設定]  二維數組調用 $v.名-->
	<!-- 1循環打印商品數組
	2表格隔行換色<tr {if $v@iteration%2==1}bgcolor="blue"{/if}><td>{$v@iteration}</td>
	3 first 只有第一行商品號背景色<tr {if $v@first}bgcolor="blue"{/if}>-->
	{/literal}

	<table>
 	<tr><td>商品號</td><td>商品名</td><td>價格</td></tr>

 	{foreach $goods as $k=>$v}
 	<tr {if $v@first}bgcolor="blue"{/if}><td>{$v@iteration}</td><td>{$v.goods_name}</td><td>{$v.shop_price}</td></tr>
	{/foreach}
	</table>

	<!-- section 循環,格式:name,loop字段必須
	loop循環數組=$source
	name屬性代表每次循環的循環單元的臨時變量
	把$source每循環的單元賦於name 自定義的 字段 -->

	<table>
 	<tr><td>號</td><td>商品名</td><td>價格</td></tr>

 	{section name=g loop=$goods}
 	<tr><td>{$goods[g].goods_id}</td><td>{$goods[g].goods_name}</td><td>{$goods[g].shop_price}</td></tr>
	{/section}
	</table>
	<!-- $source一定是索引數組 每循環一次key給g,g當goods的那一輪的key -->

	<!-- while循環 -->
	{while $age<25}
	{$age++}小於25
	{/while}

</body>
</html>




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章