模板开发 1
更新于 2026-10-13
模板开发 · 变量与过滤器
一、变量来源
模板里的变量有三种来源,优先级从高到低:
- 控制器显式赋值(
{cms:...}标签产生的局部变量)
- 全局注入变量(见下表)
- 系统内置变量
全局注入变量
| 变量 | 类型 | 说明 | |
|---|---|---|---|
$cat | array | 当前栏目(直接是数组,不是对象) | |
$cate | array | 当前栏目的别名写法,兼容旧模板 | |
$content | array | 当前内容(详情页) | |
$siteName | string | 站点名称 | |
$siteLang | string | 当前语言代码 | |
$seoTitle | string | 当前页 SEO 标题 | |
$seoKeywords | string | 关键词 | |
$seoDescription | string | 描述 | |
$hreflangHtml | string | hreflang 备用地址(`\ | raw` 输出) |
$langLinks | array | 语言切换链接 | |
$navList | array | 主导航 | |
$breadcrumb | array | 面包屑 | |
$user | array\ | null | 当前登录用户 |
除列表数据外,一律用数组直取,便于 IDE 提示与调试:
{$cat.name}而不是{$cat->name}。
二、内容字段
contentlist / 详情页的字段来自模型定义,常用字段:
| 字段 | 说明 |
|---|---|
id | 内容 ID |
title | 标题 |
url | 详情地址(已按伪静态规则生成) |
summary | 摘要 |
content | 正文 HTML |
thumb | 缩略图地址 |
publish_time | 发布时间戳 |
catid | 所属栏目 |
| 扩展字段 | 按模型字段名直接取,如 {$item.price} |
三、过滤器
变量可链式调用过滤器,用 | 分隔:
{$item.title|substr=0,20}
{$item.content|str_replace="\n","<br>"|raw}
{$item.publish_time|date="Y-m-d",###}
{$item.title|htmlspecialchars}
{$item.price|number_format=2}
常用过滤器:
| 过滤器 | 用法 | 说明 | |
|---|---|---|---|
raw | `{$html\ | raw}` | 不转义输出(富文本) |
date | `{$ts\ | date="Y-m-d"}` | 时间戳格式化 |
substr | `{$t\ | substr=0,20}` | 截断 |
str_replace | 字符串替换 | ||
number_format | 数字格式化 | ||
default | `{$x\ | default="暂无"}` | 缺省值 |
默认开启了
default_filter=htmlentities,普通{$var}会自动转义,安全。
四、常用函数
模板中可直接调用助手函数:
{:theme_static('css/style.css')} 主题静态资源
{:url('/list/9.html')} 生成地址
{:__('SearchTotal',['count'=>$n])} 语言包
{:money($item.price)} 分 → 元
{:datetime_at($item.publish_time)} 时间戳 → 日期
五、判断与默认值
{if empty($item.thumb)}
<img src="{:theme_static('images/placeholder.png')}" alt="">
{else /}
<img src="{$item.thumb}" alt="{$item.title}">
{/if}
<span>{$item.summary|default="暂无摘要"}</span>
六、调试
{:dump($cat)}
{:dump($content)}
生产环境请移除调试输出。