例如:
common.php写入如下代码
<?php
// 应用公共文件
//加载thinkphp 类 / 助手函数
use think\Request;
use think\Session;
use think\Controller;
//获取当前域名
function getdomain(){
$request = Request::instance();
//获取当前域名 携带https 或 http
$url_https_wshx=$request->domain();
return $url_https_wshx;
}
然后在控制中 Index.php
<?php
namespace app\admin\controller;
use think\Controller;
class Index extends Controller
{
//获取当前域名
public function index(){
$domain=getdomain();//直接调用 common.php 公共函数文件 自动加载的
var_dump($domain);//打印
//渲染
//return $this->fetch('index');
}
}
然后在模板中 Index.html调用
{$urlstr|getdomain}
{$d['title']|mb_substr=0,10,'utf-8'}
注意:$urlstr必须在控制器中给模板赋值过
调用很简单,只需要在变量后面加“|”符,然后跟着函数,和其他的thinkPHP模板中调用函数一样。实例:{$info.addtime|timeFormat=###},说明:info数组变量中addtime元素为时间戳,经过函数处理后就返回格式化后的字符串了,如果addtime和现在时间差距在1个小时以内就好显示为类似“5分钟前”的字符串,如果大于1个小时小于1天,就会显示类似“4个小时前”,如果大于一天则显示格式化后的日期字符串,如“2014-6-26 15:34”。
还有一个好处是thinkPHP还支持函数的连贯操作,例如{$info.addtime|date="Y-m-d H:i",###|dateFormat=###},具体的大家去尝试吧!
注意:自定义函数要放在项目应用目录/common/common.php中。 这里是关键。
模板变量的函数调用格式:{$varname|function1|function2=arg1,arg2,### }
说明:
{ 和 $ 符号之间不能有空格,后面参数的空格就没有问题;
###表示模板变量本身的参数位置 ;
支持多个函数,函数之间支持空格 ;
支持函数屏蔽功能,在配置文件中可以配置禁止使用的函数列表 ;
支持变量缓存功能,重复变量字串不多次解析。
使用例子:
{$webTitle|md5|strtoupper|substr=0,3}
{$number|number_format=2}
{$varname|function1|function2=arg1,arg2,### }
实例:
复制代码代码如下:
function Cate($cid){
$Cate=D('Cate');
$Cate=$Cate->where('id='.$cid)->find();
return $Cate['title'];
}
我想在模板中调用这个函数则在模板中可以这样写
{$vo.cid|cate=###}