smarty模板的数据变量有哪些,又该如何调用?
2022-11-18 09:21:57
163
{{single.collect_count}}
定义:模板变量,即在模板中被分配的变量,以及如何使用Smarty规则在模板中解析变量。

Smarty模板中,我们将模板中的变量分为三类。

  • PHP分配变量,即利用assign方法分配的变量。

  • smarty保留变量,包括超全局预定义变量smarty的内置变量。

  • 自定义变量,用户在模板中去定义变量。

1.PHP分配变量,理论上PHP可以分配任意数据类型给模板进行解析,通常数据其实也就三种:

  • 标量数据:直接使用标记输出的数据。

  • 数组数据:在smarty模板中可以使用下标或者通过"."+下标来实现。

  • 对象数据:在smarty模板中是通过对象访问符来实现访问。

<?phprequire 'smarty/Smarty.class.php';$smarty=new Smarty();// $smarty->left_delimiter="<{";// $smarty->right_delimiter="}>";$smarty->template_dir = 'templates/'; //实际模板所在目录,如果没有会在根目录下查找//普通数据$smarty->assign('hello',"hello world");//数组$smarty->assign('arr1',array(1412,14,23,456));$smarty->assign('arr2',array('name'=>'张三','sex'=>'男'));//对象class Person{public $name='陈平安';public $perr='saber';}$smarty->assign('object1',new Person());$smarty->display('model.html');?>
登录后复制
<!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='name' value='Sun'}{$name}</body></html>
登录后复制

推荐:php教程,php视频教程

php入门到就业线上直播课:立即学习
全程直播 + 实战授课 + 边学 + 边练 + 边辅导

以上就是smarty模板的数据变量有哪些,又该如何调用?的详细内容,更多请关注php中文网其它相关文章!

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}