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>




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