Приложение: НОВИНИ
Ще използваме класът описан по-напред в статията, който ще се го наречен db.class.php. Ще ни трябва и smarty разположете го в папка smarty. Сега направете папка templates и една templates_c. Както и един файл news.php, който ще бъде нашият скрипт показващ новините.
Преди да разгледаме кодът нека да обърнем внимание на съдържанието на темплейта и по специално на частта от него с която ще показваме новините.
CODE1
2
3
4
5
6
7
8
9
10
11
| {foreach name=probe item=Items from=$news}
<div class="{if $smarty.foreach.probe.iteration is not even}left{else}right{/if}">
заглавие: <b>{$Items.0}</b>
<hr width="100%" />
<img src="{$Items.2}" align="left" />
{$Items.1}
</div>
{if $smarty.foreach.probe.iteration is not odd}<br clar="all" />
{elseif $smarty.foreach.probe.last}<br clar="all" />
{/if}
{foreach} |
Какво правим? Значи със foreach обхождаме масива и показваме елементите му. $smarty.foreach.probe.iteration е номера на итерацията това е специалнна променлива във smarty. $променлива is not even е делене по модул на 2, като резултата е true ако остатъка е 0. По този начин определяме четно и нечетно число, като нечетното е в ляво, а четното в дясно. is not odd e делене по модул на 2 като връща true ако остатъка е различен от 0. С помощта на това определяме дали да почистим всичко и да почнем следващите две новини. Но ако имаме 3 новини няма да сме „почистили” затова към този if добавяме и elseif, ако това е последният елемент почиства ме :).
News.php
CODE1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
| <?php
/*
testov news.php
*/
@require "db.class.php";
@require "smarty/Smarty.class.php";
//db connect
$db = new db("mysql", "localhost", "root", "", "probe");
$db->connect();
//tempaltes
$tpl = new Smarty();
$tpl->template_dir = './templates';
$tpl->compile_dir = './templates_c';
$sql = "SELECT title, text, imgname FROM news ORDER BY id DESC";
$res = $db->pages($sql, 6, "?category=mysite");
$tpl->assign('str', $res);
$res = $db->select($sql, 6, 1);
$tpl->assign('news', $res);
$tpl->display('news.tpl');
$db->disconnect();
?>
News.tpl
<html>
<head>
<title>script: news</title>
<style>
.left {
float: left;
width: 300px;
}
.right{
float: right;
width: 300px;
}
</style>
</head>
<body>
{foreach name=probe item=Items from=$news}
<div class="{if $smarty.foreach.probe.iteration is not even}left{else}right{/if}">
заглавие: <b>{$Items.0}</b>
<hr width="100%" />
<img src="{$Items.2}" align="left" />
{$Items.1}
</div>
{if $smarty.foreach.probe.iteration is not odd}<br clar="all" />
{elseif $smarty.foreach.probe.last}<br clar="all" />
{/if}
{foreach}
<hr />
Страници: {str}
</body>
</html> |
Тази статия е публикувана под:
Creative Commons Attribution-ShareAlike 2.5 License