且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

smarty教程系列2--section1

更新时间:2022-01-21 20:48:48

第二课 smarty基本语法(1)
好了有了上一节课的安装,这节课我们看看smarty的基本语法
我们知道smarty是为了把php和美工制作的模板部分尽量做到分离,这样程序做程序时可以不必等到美工的页面出来之后在做前台这部分程序,
smarty起到了一个中间桥梁的作用,这样需要我们的程序员和美工都要了解smarty的语法,好了我们先看看模板设计者部分(也就是美工这一部分),
我们简单看一个模板test.tpl:

smarty教程系列2--section1<html>
smarty教程系列2--section1<head><title><{$title}></title></head>
smarty教程系列2--section1<body>
smarty教程系列2--section1我的名字是<{$name}>,我来自<{$city}>.
smarty教程系列2--section1</body>
smarty教程系列2--section1</html>


test.php关键部分部分:

smarty教程系列2--section1$title="学习smarty基本语法部分";
smarty教程系列2--section1$name="xcf007";
smarty教程系列2--section1$city="威海";
smarty教程系列2--section1
$tpl->assign("title",$title);
smarty教程系列2--section1$tpl->assign("name",$name);
smarty教程系列2--section1$tpl->assign("city",$city);


这里就是简单把数据赋给模板变量.


smarty是编译模板,也就是说它首先根据模板去生成一个php文件,我们运行后会发现在template_c目录生成一个类似
%%45^45E^45E480CD%%test.tpl.php这样名字的文件,这就是smarty根据模板编译生成的一个文件。

其实它就是扫描一下tpl文件,定界符外的直接输出到那个php临时文件里,而定界符内的部分,它会处理
比如 我的名字是<{$name}>,我来自<{$city}>.他就会把<{$name}>替换成<?php echo $name;?>类似这个样子,当然实际中他是$this->_tpl_vars['Name'];我们为了简单起见。


很多php程序员不用smarty时,有的就用include方式。
比如

test.php:

smarty教程系列2--section1$title="学习smarty基本语法部分";
smarty教程系列2--section1$name="xcf007";
smarty教程系列2--section1$city="威海";
smarty教程系列2--section1
include 'index.tpl';

而index.tpl变成了:

smarty教程系列2--section1<html>
smarty教程系列2--section1<head><title><?php echo $title;?></title></head>
smarty教程系列2--section1<body>
smarty教程系列2--section1我的名字是<?php echo $name;?>,我来自<?php echo $city;?>.
smarty教程系列2--section1</body>
smarty教程系列2--section1</html>

好了,这个include方式,大家做小东西不妨试试。

了解smarty的机制,看看语法:
1.smarty注释
看看模板任意如何做注释,因为可能有时候做模板时需要对模板变量做一下注释,
注意不是html注释,那个会出现在将来静态页面源代码中,我们这个是对模板注解的,只想出现在模板文件里。
好了是 定界符带个星号,如<{* 这里是模板注释 *}>

这个注释模板编译时会忽略,不会出现在那个临时的php文件里面。

待续...






 本文转自 xcf007 51CTO博客,原文链接:http://blog.51cto.com/xcf007/156835,如需转载请自行联系原作者