php之Smarty基本文法和三大變數,smarty基本文法三大
在Smarty模板中主要都是以變數為主,下面就是有關Smarty的三大變數以及一些普通的用法
首先在根目錄下建立要用到的檔案基本和上一次一樣,configs是設定檔夾
一、從PHP中分配的變數
用$smarty->assign()
$smarty->display()
首先先編寫初始化的php代碼,和上一篇的 conn.inc.php 一樣
<?php include "init.inc.php"; //assign方法 $smarty->assign("title","11111111"); $smarty->assign("content","2222222222"); //分配一個關聯陣列,用的較少 $smarty->assign(array("author"=>"何栘烽","time"=>date("Y-m-d H:i:s"))); //註冊函數 $smarty->registerPlugin("function","myfun","test"); //註冊外掛程式,將test函數註冊成myfun function test($args){ //args=array("size"=>7, "color"="yellow", "num"=>5, "connect"=>"3333333") //迴圈遍曆出 $str=""; for($i=0; $i<$args["num"]; $i++){ $str.='<font color="'.$args['color'].'" size="'.$args['size'].'">'.$args["content"].'</font><br>'; } return $str; } //數組 $smarty->assign("contacts",array("0575-1241243","kefeng.hyf@gmail.com", array("243214124", "45345"))); //對象 class Person{ public $name="kefeng"; function say(){ return $this->name."hhhhhhhh"; } } $smarty->assign("p",new Person()); $smarty->display("demo.html"); //顯示的模板
demo.html:
<html><head><title><{ $title }></title><style>body {color:red;}</style></head><body> content:<{$content}><br> content:<{$content}><br> content:<{$content}><br> author:<{$author}><br> time:<{$time}><br> time:<{myfun()}><br> time:<{date("Y-m-d")}><br><img src="img.gif" /><br><{myfun size="7" color="yellow" num="5" content="3333333"}><{$contacts[0]}><br><{$contacts[2][0]}><br><br><{$p->name}><br><{$p->say()}><br><br></script></body></html>
二、從設定檔中讀取變數
這裡需要創一個 configs 檔案夾,裡面設定檔 test.conf
test.conf:
bodycolor=#3e3e3ebodybgcolor=yellowborder=10align=centerwidth=800bgcolor=gray[index]one=11111[list]two=22222[content]three=33333
在demo.php 中開啟session
<?php //session_start(); include "init.inc.php"; $_SESSION["username"]="admin"; $smarty->display("demo.html"); //顯示的模板
注意的是:
載入設定檔:<{config_load "test.conf"}>
讀取:<{#內容#}>
載入地區檔案要用到第二個參數:<{config_load "test.conf" section="index"}>
demo.html :中,這裡寫一些標頭檔,以及載入代碼
<html> <head> <title><{ $title }></title> <style> body {color:red;} </style> </head> <{config_load "test.conf" section="index"}> <body text="<{ #bodycolor# }>" bgcolor="<{#bodycolor#}>"> ....... ....... <{#one#}><br> <{#two#}><br> <{#three#}><br> ...... </body></html><span style="white-space:pre"></span>
三、保留變數
主要有: $_GET
$_POST
$_SESSION
$_SERVER
$_ENV
<{$smarty()}>
<p><{$smarty.session.username}><br><{$smarty.now}><br><{$smarty.const.ROOT}><br><{$smarty.const.M_PI}><br><{$smarty.current_dir}><br>