教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 Smarty模板快速入门

Smarty模板快速入门

发布时间:2023-05-11   编辑:jiaochengji.com
教程集为您提供Smarty模板快速入门等资源,欢迎您收藏本站,我们将为您提供最新的Smarty模板快速入门资源

Smarty模板快速入门
引言

      现在论坛中部分会员在学习Smarty,故找了这篇快速入门的文章供大家学习。
    其实在PHP的世界里已经出现了各式各样的模板类(25种PHP开发模板[超级经典]),但就功能,速度,易学三方面综合来说Smarty还是一直处于领先地位,因为Smarty的功能相对强大,所以使用起来比其他一些模板类稍显复杂了一点。现在就用30分钟让您快速入门。

二. 赋值

      在模板文件中需要替换的值用大括号{}括起来,值的前面还要加$号。例如{$hello}。这里可以是数组,比如{$hello.item1},{$hello.item2}…
      而PHP源文件中只需要一个简单的函数assign(var , value)。
      简单的例子:
      *.tpl:

      Hello,{$exp.name}! Good {$exp.time}
      *.php:

      $hello[name] = “Mr. Green”;
      $hello[time]=”morning”;
      $smarty->assign(“exp”,$hello);

      output:

      Hello,Mr.Green! Good morning

三. 引用
      网站中的网页一般header和footer是可以共用的,所以只要在每个tpl中引用它们就可以了。
      示例:*.tpl:

    {include file="header.tpl"}

 

      {* body of template goes here *}

 

      {include file="footer.tpl"}


  四. 判断

      模板文件中可以使用if else等判断语句,即可以将一些逻辑程序放在模板里。"eq", "ne", "neq", "gt", "lt", "lte", "le",  "gte"  "ge", "is even", "is odd", "is not even", "is not odd", "not", "mod", "div by", "even by", "odd by","==","!=",">", "<","<=",">="这些是if中可以用到的比较。看看就能知道什么意思吧。
      示例:

      {if $name eq "Fred"}

                    Welcome Sir.

    {elseif $name eq "Wilma"}

                    Welcome Ma'am. 
    {else}

                    Welcome, whatever you are.
    {/if}


  五. 循环

      在Smarty里使用循环遍历数组的方法是section,如何赋值遍历都是在模板中解决,php源文件中只要一个assign就能解决问题。
      示例:

{* this example will print out all the values of the $custid array *}

{section name=customer loop=$custid}
              id: {$custid[customer]}<br>
{/section}

OUTPUT:

id: 1000<br>
id: 1001<br>
id: 1002<br>

  六. 常见问题

      Smarty将所有大括号{}里的东西都视为自己的逻辑程序,于是我们在网页中想插入javascript函数就需要literal的帮忙了,literal的功能就是忽略大括号{}。
      示例:
{literal}

      <script language=javascript>

            function isblank(field) {
                      if (field.value == '')

                              { return false; }
                      else

                              {
                              document.loginform.submit();

                              return true;

                              }

            }
      </script>
{/literal}

您可能感兴趣的文章:
smarty 模板if else使用实例与入门教程
php smarty 基础
有关smarty模板引擎生成静态页的关键代码
用 Smarty 分离 PHP 应用程序中的形式与功能
(图)php模板引擎Smarty详细介绍
有关smarty的基本设置
php模板引擎有哪些
smarty结合xajax检测用户名
smarty结合xajax检测用户名简单实例
在php中配置使用smarty模板引擎

[关闭]
~ ~