学习
注意,使用Smarty,一般来说,可以直接将Smarty.class.php
拷贝到项目中就行,可以是项目libs/
目录下。
注释
单行注释:
{* smarty *} 是模板的注释。 虽然不是必须的,但在模板内添加注释这是个很好的习惯。 它可以帮助识别出文件类型,而不需要看后缀。 比如说,代码编辑器可以识别该文件并自动语法高亮。
多行注释:
{*
xxx
*}
变量
模板变量以美元符号$开头,由字母、数组和下划线组成,和php变量相似。变量可以引用数字索引或非数字索引的数组,对象的属性和方法等。
eg:
这个是index.php
:
<?php
/**
* Created by PhpStorm.
* User: ldl
* Date: 2018/7/5
* Time: 上午11:52
*/
define('SMARTY_DIR', '/usr/local/lib/smarty-3.1.32/libs/');
require_once(SMARTY_DIR . 'Smarty.class.php');
$smarty = new Smarty();
$smarty->setTemplateDir('/Users/luowensheng/Desktop/TestIOS/smarty-test01/templates/');
$smarty->setCompileDir('/Users/luowensheng/Desktop/TestIOS/smarty-test01/templates_c/');
$smarty->setConfigDir('/Users/luowensheng/Desktop/TestIOS/smarty-test01/configs/');
$smarty->setCacheDir('/Users/luowensheng/Desktop/TestIOS/smarty-test01/cache/');
$smarty->assign('name', 'Malin');
//$smarty->debugging = true;
$smarty->display('index.tpl'); // 这里的后缀不重要,可以是index.html。这里展示index.tpl页面。我们运行访问`index.php`这个页面,那么我们将会看到`index.tpl`。
变量的来源
模板中的变量主要来源有三种。
4.1.1、是由原php文件中分配过来的。
$smarty->assign(‘name’,’韩灵稚’); #在源php文件中分配
<span>你好, {$name}</span> #在模板文件中使用
4.1.2、是由配置文件中分配过来的。
$smarty->configLoad(“configs/my.conf”) #在源php文件中载入配置文件,也可以在模板中载入
<span style=”color:{#fontcolor#}; font-size:{#fontsize#};”>这是{#gv#}</span><br /> #在模板文件中使用
4.1.3、是在模板文件中创建的。
{assign var=”name” value=”韩灵稚” nocache=”false”scope=”global”}
在模板中定义的变量,如果之前定义了相同的变量,则以最后一次定义为准。
{$name=”韩灵稚”} #给变量直接赋值,如果该变量原来不存在,自动创建,3.0新特性。
{assign var=foo value=[1,2,3]} #定义普通数组变量
{assign var=foo value=['y'=>'yellow','b'=>'blue']} #定义关联数组
{assign var=foo value=[1,[9,8],3]} #定义数组中的数组
{foo的一个元素
<span>你好, {$name}</span> #在模板文件中使用
网友评论