天天看點

smarty教程系列2-section2

我們接着上次的内容講解,首先這次把smarty定界符改了:

$tpl->left_delimiter = "<!--{";//左定界符

$tpl->right_delimiter = "}-->";//右定界符

2.變量

下面是通過php指派(assign)方式配置設定值:

1.)簡單變量

通過$smarty->assign('name','xcf007');

配置設定的變量,在模闆裡面我們可以像php中那樣調用

如<!--{$name}-->

2.)數組

這是簡單的變量形式,下面看看數組的:

關鍵代碼部分

chap2.php:

$tpl->assign('me',array('xcf007','山東威海',26));

模闆chap2.tpl(注意模闆字尾任意,習慣用tpl你也可以用html等):

我的名字是<!--{$me[0]}-->,我來自<!--{$me[1]}-->,本人年齡<!--{$me[2]}-->.

再看看關聯數組的:

php部分:

$tpl->assign('me',array('name'=>'xcf007','city'=>'山東威海','age'=>26));

模闆部分:

我的名字是<!--{$me.name}-->,我來自<!--{$me.city}-->,本人年齡<!--{$me.age}-->.

注意關聯數組的引用方式,用的點.符号。

對于嵌套的數組道理一樣,類似$me.name.firstname這個樣子。

3.)對象

chap2.php,簡單的一段代碼,屬性公開:

class Person

{

public $name;

public $city;

public $age;

function __construct($name,$city,$age)

    $this->name=$name;

    $this->city=$city;

    $this->age=$age;

}

$me=new Person('xcf007','山東威海',26);

$tpl->assign('me',$me);

模闆chap2.tpl:

我的名字是<!--{$me->name}-->,我來自<!--{$me->city}-->,本人年齡<!--{$me->age}-->.

注意對象通路操作符,這裡是->

下面我們看看如何從配置檔案擷取值:

<?php

require_once("inc/smarty.inc.php");//引入smarty

$tpl->assign('title',"讀取配置檔案變量");

$tpl->display('chap2.tpl');

?>

在configs檔案夾下建立menu.conf檔案:

[chinese]

home = "首頁"

introduction = "公司介紹"

contact = "聯系我們"

[english]

home = "Home"

introduction = "Introduction"

contact = "Contact Us"

模闆檔案chap2.tpl:

<!--{config_load file="menu.conf" section="chinese"}-->

<html>

<head><title><!--{$title}--></title></head>

<body>

<p><a href="#"><!--{#home#}--></a> | <a href="#"><!--{$smarty.config.introduction}--></a> | <a href="#"><!--{#contact#}--></a></p>

</body>

</html>

通過config_load的smarty模闆函數加載配置檔案menu.conf,裡面的chinese部分(就是中文菜單啦)

如果加載英文的可以,<!--{config_load file="menu.conf" section="english"}-->

模闆變量引用方式可以用#變量名字#方式,也可以$smarty保留變量的方式就是$smarty.config.變量名字的方式,各有特色。

##方式簡單些,但有時出在引号裡面時,就得考慮用保留變量方式了。

待續...