首頁  >  文章  >  後端開發  >  smarty模板的資料變數有哪些,又該如何呼叫?

smarty模板的資料變數有哪些,又該如何呼叫?

autoload
autoload原創
2021-03-08 11:02:051317瀏覽

定義:模板變數,即在模板中被指派的變數,以及如何使用Smarty規則在模板中解析變數。

Smarty模板中,我們將模板中的變數分成三類。

  •       PHP分配變量,即利用assign方法指派的變數。

  •       smarty保留變量,包含超全域預定義變數smarty的內建變數。

  •       自訂變量,使用者在範本中去訂變數。

  1.PHP分配變量,理論上PHP可以分配任意資料型別給模板解析,通常資料其實也就三種:

  • 標量資料:直接使用標記輸出的資料。

  • 陣列資料:在smarty模板中可以使用下標或透過"." 下標來實現。

  • 物件資料:在smarty範本中是透過物件存取符來實現存取。

<?php
    require &#39;smarty/Smarty.class.php&#39;;
    $smarty=new Smarty();
    // $smarty->left_delimiter="<{";
    // $smarty->right_delimiter="}>";
    $smarty->template_dir = &#39;templates/&#39;;   //实际模板所在目录,如果没有会在根目录下查找
    
    
    //普通数据
    $smarty->assign(&#39;hello&#39;,"hello world");
    //数组
    $smarty->assign(&#39;arr1&#39;,array(1412,14,23,456));
    $smarty->assign(&#39;arr2&#39;,array(&#39;name&#39;=>&#39;张三&#39;,&#39;sex&#39;=>&#39;男&#39;));
    //对象
    class Person{
        public $name=&#39;陈平安&#39;;
        public $perr=&#39;saber&#39;;
    }
    $smarty->assign(&#39;object1&#39;,new Person());
    $smarty->display(&#39;model.html&#39;);
?>
<!DOCTYPE html>//模板 model.html
<html>
<head>
    <title></title>
</head>
<body>
     {$hello}这是templates下面的模板 <br>
     这是索引数组:{$arr1[0]}---{$arr1[1]}------{$arr1[2]}<br>
     这是索引数组:{$arr1.0}---{$arr1.1}------{$arr1.2}<br>
     这是关联数组:{$arr2.name}-----{$arr2.sex}<br>
     这是对象:{$object1->name}-----------{$object1->perr}<br>
</body>
</html>

  2.Smarty保留變數:是smarty考慮到使用者會需要經常使用的系統變量,或是內部變數。這類變數通常以$smarty開始,然後是各類關鍵字,多次造訪。

  • GET資料:{$smarty.get.名字}

  • POST資料:{$smarty.post.名字}

  • session資料:{$smarty.session.名字}

  • #cookie資料:{$smarty.cookies.名字}

  • #REQUEST資料:{$smarty.request.名字}

  • #server資料:{$smarty.server.大寫名字}

  • #時間戳記:{$smarty.now}

  • 模板路徑:{$smarty.current_dir}

  • 模板名稱:{ $smarty.template}

  • 設定檔:{$smarty.config.設定檔名}

<html>
   	<header></header>
    <body>
        	GET数据:{$smarty.get.name}
	  	POST数据:{$smarty.post.name}
		session数据:{$smarty.session.username}
		cookie数据:{$smarty.cookies.username}
		REQUEST数据:{$smarty.request.name}
		server数据:{$smarty.server.SERVER_NAME}
		时间戳:{$smarty.now}
		模板路径:{$smarty.current_dir}
		模板名字:{$smarty.template}
    </body>
</html>

  3.自訂變數:Smarty為了在模板中可以靈活的對資料進行處理,允許設定變數:{assign var='變數名稱' value='變數值'}。

<html>
    <header></header>
    <body>
        {assign var=&#39;name&#39; value=&#39;Sun&#39;}
        {$name}
    </body>
</html>

推薦:php教學,php影片教學

以上是smarty模板的資料變數有哪些,又該如何呼叫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn