教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 smarty入门教程五

smarty入门教程五

发布时间:2023-05-11   编辑:jiaochengji.com
教程集为您提供smarty入门教程五等资源,欢迎您收藏本站,我们将为您提供最新的smarty入门教程五资源

例5: 使用模板内置流程控制语句进行一行多单元格内容输出, 也就是在视觉上smarty每记输出几条记录:

example5.tpl


<html>
<head>
<title>一行输出多条记录</title>
</head>
<body>
<table>
<tr>
{section name=loop loop=$News step=1}
{if $smarty.section.loop.index % 4==0}
</tr>
<tr>
{/if}
<td>{$News[loop].newsID}</td>
<td>{$News[loop].newsTitle}</td>
{/section}
</tr>
</table>
</body>
</html>
example5.php

 

<?php
/*********************************************
*
* 文件名: example5.php
* 作 用: 显示实例程序5
*
* 作 者: 大师兄
* Email: teacherli@163.com

* 修 正: forest
*********************************************/

require_once ("./comm/Smarty.class.php");

$smarty = new Smarty();
$smarty->template_dir = './templates/';
$smarty->compile_dir = './templates_c/';
$smarty->config_dir = './configs/';
$smarty->cache_dir = './cache/';
$smarty->caching = false;

$array[]= array("newsID"=>"001", "newsTitle"=>"第1条新闻");
$array[]= array("newsID"=>"002", "newsTitle"=>"第2条新闻");
$array[]= array("newsID"=>"003", "newsTitle"=>"第3条新闻");
$array[]= array("newsID"=>"004", "newsTitle"=>"第4条新闻");
$array[]= array("newsID"=>"005", "newsTitle"=>"第5条新闻");
$array[]= array("newsID"=>"006", "newsTitle"=>"第6条新闻");
$array[]= array("newsID"=>"007", "newsTitle"=>"第7条新闻");
$array[]= array("newsID"=>"008", "newsTitle"=>"第8条新闻");


$smarty->assign("News", $array);

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


==================================================
example5.php输出内容:
==================================================
<html>
<head><title>一行输出多条记录</title></head>
<body>
<table>
<tr>

</tr>
<tr>
<td>001</td>
<td>第1条新闻</td>

<td>002</td>
<td>第2条新闻</td>

<td>003</td>
<td>第3条新闻</td>

<td>004</td>
<td>第4条新闻</td>

</tr>
<tr>
<td>005</td>
<td>第5条新闻</td>

<td>006</td>
<td>第6条新闻</td>

<td>007</td>
<td>第7条新闻</td>

<td>008</td>
<td>第8条新闻</td>
</tr>
</table>
</body>
</html>

说明:本来还可以优化,使得第一行不输出一个空行的<tr> </tr>,但是学习程序,简单为好,先就这么用了. 在这里说明一下:


{section name=loop loop=$News step=1}
{if $smarty.section.loop.index % 4 == 0}
</tr>
<tr>
{/if}
<td>{$News[loop].newsID}</td>
<td>{$News[loop].newsTitle}</td>
{/section}

 

{section}{/section}指的是一个循环部分,在下一节会有详细的介绍,我们主要来看看这一句:
{if $smarty.section.loop.index % 4 == 0}
$smarty.section.loop指出$smarty的实例中的section段有一个叫loop的部分, 它有一个属性叫index, 它的表示当前循环的索引值,从0开始递增,我们把它%4后与0相比较,也就是说,如果当前的索引值是4的倍数,它就输出一个</tr><tr>,否则执行下面的部分,
很简单的就解决了一个在程序上实现起来很麻烦的事情.这里我仅演示的是如何使用{if}语句功能,实现这个功能在Smarty的模板中还有一个非常方便的办法:{cycle},使用的例子如下所示:


PHP:[Copy to clipboard]
{section name=rows loop=$data}
<tr bgcolor="{cycle values="#D4D0C8,#EEEEEE"}">
<td>{$data[rows]}</td>
</tr>
{/section}

 

您可能感兴趣的文章:

[关闭]
~ ~