Discuz 模板(.htm)基於模板引擎語法,通過全局變量 $_G 判斷用戶狀態,實現「登錄前/後顯示不同內容」、「管理員專享功能」等常見需求。
<!--{if $_G['uid']}-->
<!-- 已登錄用戶看到的內容 -->
歡迎回來,<a href="home.php?mod=space&uid={$_G['uid']}">{$_G['username']}</a> |
<a href="member.php?mod=logging&action=logout&formhash={FORMHASH}">退出</a>
<!--{elseif empty($_G['uid'])}-->
<!-- 未登錄游客看到的內容 -->
<a href="member.php?mod=logging&action=login">登錄</a> |
<a href="member.php?mod=register">註冊</a>
<!--{/if}-->
<!--{if $_G['adminid'] == 1}-->
<!-- 超級管理員專享:後台入口、SQL 執行、緩存更新等 -->
<a href="admincp.php" target="_blank">管理中心</a>
<!--{/if}-->
進階:判斷管理組權限
<!--{if $_G['adminid'] > 0}--> <!-- 任意管理組(1=超管, 2=管理員, 3=版主) -->
<!--{if in_array($_G['groupid'], [1,2,3])}--> <!-- 用戶組 ID 判斷 -->
| 變量 | 含義 | 類型 | 示例 |
|---|---|---|---|
$_G['uid'] | 用戶 UID,0=游客 | int | 12345 |
$_G['username'] | 用戶名 | string | admin |
$_G['groupid'] | 用戶組 ID | int | 10 (註冊會員) |
$_G['adminid'] | 管理身份:0=非管理,1=超管,2=管理員,3=版主 | int | 1 |
$_G['formhash'] | 表單令牌,防 CSRF | string | abc123def |
$_G['setting'] | 站點設置數組 | array | ['sitename'=>'xxx'] |
$_G['style'] | 當前風格信息 | array | ['styleid'=>1] |
$_G['forum'] | 當前版塊信息(版塊頁) | array | ['fid'=>2, 'name'=>'討論區'] |
$_G['thread'] | 當前主題信息(帖子頁) | array | ['tid'=>100, 'subject'=>'標題'] |
<!--{if $_G['uid']}-->
<!-- 編輯器區域 -->
<textarea name="message" id="message"></textarea>
<button type="submit">發表</button>
<!--{else}-->
<div class="login-prompt">
請 <a href="member.php?mod=logging&action=login&referer={echo rawurlencode(dreferer());}">登錄</a> 後發帖
</div>
<!--{/if}-->
<!--{loop $threadlist $thread}-->
<tr>
<td><a href="forum.php?mod=viewthread&tid={$thread[tid]}">{$thread[subject]}</a></td>
<!--{if $_G['adminid'] == 1 || $_G['uid'] == $thread[authorid]}-->
<td class="mod">
<a href="forum.php?mod=modcp&action=stick&tid={$thread[tid]}">置頂</a> |
<a href="forum.php?mod=modcp&action=highlight&tid={$thread[tid]}">高亮</a> |
<a href="forum.php?mod=modcp&action=del&tid={$thread[tid]}">刪除</a>
</td>
<!--{/if}-->
</tr>
<!--{/loop}-->
<!--{if $_G['uid']}-->
<div class="user-panel">
<img src="{avatar($_G[uid],small)}" /> {$_G['username']}
<a href="home.php?mod=spacecp&ac=profile">設置</a> |
<a href="home.php?mod=space&uid={$_G['uid']}">主頁</a>
</div>
<!--{else}-->
<form id="lsform" action="member.php?mod=logging&action=login&loginsubmit=yes" method="post">
<input type="hidden" name="formhash" value="{FORMHASH}" />
<input type="text" name="username" placeholder="用戶名" />
<input type="password" name="password" placeholder="密碼" />
<button type="submit">登錄</button>
</form>
<!--{/if}-->
<!--{if ...}--> / <!--{elseif ...}--> / <!--{/if}-->:條件判斷<!--{loop $arr $key $val}--> ... <!--{/loop}-->:遍歷數組{$var}:輸出變量(已 htmlspecialchars){echo ...}:執行 PHP 表達式並輸出{eval ...}:執行 PHP 代碼不輸出data/template/ 下編譯文件Discuz 模板引擎雖老但極其強大,掌握 $_G 全局變量與條件/循環語法,即可實現極靈活的動態顯示邏輯。現代二開建議:業務邏輯下沉至插件/模塊 PHP 類,模板僅負責顯示,降低耦合、提升可測試性。