PHP程序员小白到大牛集训(12期免息)

smarty模板引擎配置与模板变量

原创2018-12-10 18:34:2293
摘要:配置文件: 1、加载smarty模板引擎类库 require __DIR__. '/../libs/Smarty.class.php'; 2、使用smarty模板引擎对象  $smarty = new smarty() 3.配置四个目录,分别为模板文件目录,模板编译文件目录,缓存目录,配置目录  ①、$smart
配置文件:
1、加载smarty模板引擎类库
require __DIR__. '/../libs/Smarty.class.php';
2、使用smarty模板引擎对象
 $smarty = new smarty()
3.配置四个目录,分别为模板文件目录,模板编译文件目录,缓存目录,配置目录
 ①、$smarty->setTemplateDir(__DIR__.'/../temp');
 ②、$smarty->setCompileDir(__DIR__ . '/../temp_c')
 ③、$smarty->setCacheDir(__DIR__ .'/../cache')
 ④、$smarty->setConfigDir(__DIR__ .'/../config')
 
模板变量:
1、定义变量,模板赋值, 在模板中使用
   $name = 'DonnieKing';
   $smarty->assign('name',$name);
   {$name}
2、索引数组 ,模板赋值,在模板中使用
   $course=['html','css','js','jQuery'];
   $smarty->assign('course',$course);
   ①{$course.1} ②{$course[1]} ③ {$course['1']}
3、关联数组,模板赋值,在模板中使用
   $book = ['name'=>'php从入门到放弃','price'=>'88','publish'=>'2016.10.30'];
   $smarty->assign('book',$book);
   {$book.name} {$book.price}
4、多维数组,模板赋值,在模板中使用
     $books = [
    ['name'=>'php从入门到放弃','price'=>'88','publish'=>'2016.10.30'],
    ['name'=>'javaScript经典讲义','price'=>'98','publish'=>'2017.1.30'],
    ['name'=>'html,css入门','price'=>'108','publish'=>'2014.5.10']
               ];
    $smarty->assign('books',$books);
    {$books.1.name}  {$books.1.price} {$books.1.publish}
5、对象,模板赋值,在模板中使用
    class Test{
    public $site =  'php中文网';
    public function welcome(){
        return '欢迎来到'.$this->site;
    }
}
    $test = new Test();
    $smarty->assign('test',$test);
    {$test->site}  {$test->welcome()}
6、自定义函数,不需要赋值(assign),直接 在模板中使用
function add($a,$b){
    return $a.'+'.$b.'='.($a+$b);
}
  {add($books.1.price,20)}   //参数可以是变量
7、常量,不需要赋值(assign),直接在模板中输出
    const NAME='DonnieKing';
    {$smarty.const.NAME}
8、系统常量, 不需要赋值(assign),直接在模板中输出
    $_POST['username'] = 'DonnieKing';
    $_GET['tel'] = 18335661677;
    $_SESSION['pass'] = sha1('123456');
  输出:
    {$smarty.post.username},{$smarty.get.tel},{$smarty.session.pass}
9、读取配置文件
    {config_load file="app.conf"}
    {$smarty.config.app_name}
    
    
  //模板渲染
$smarty->display('demo3.html');


发布手记

热门词条