:::
8-3 加入管理工具功能
- 判斷若是有登入,就在文章的資訊列加上管理工具
admin.php預設動作就是叫出編輯表單,所以,編輯時不給op也沒關係,但是一定要有id編號,才知道要改哪一篇。- 一樣請 AI 幫忙一下:
請用BootStrap5,建立一個按鈕組,包含「編輯」和「刪除」的按鈕,給Smarty5的樣板使用 編輯按鈕請連結至 admin.php?id={$news.id} 刪除按鈕請連結至 admin.php?op=delete&id={$news.id},並加入sweetalert的刪除確認後才執行。 - AI非常乖巧的完成任務,我們將以下語法存為
templates/toolbar.tpl<div class="btn-group" role="group" aria-label="操作按鈕"> <a href="admin.php?id={$news.id}" class="btn btn-primary btn-sm"> <i class="fas fa-edit"></i> 編輯 </a> <a href="#" class="btn btn-danger btn-sm" onclick="confirmDelete({$news.id}); return false;"> <i class="fas fa-trash-alt"></i> 刪除 </a> </div> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> <script> function confirmDelete(id) { Swal.fire({ title: '確定要刪除嗎?', text: "此操作無法撤銷!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: '是的,刪除它!', cancelButtonText: '取消' }).then((result) => { if (result.isConfirmed) { window.location.href = `admin.php?op=delete&id=${id}`; } }) } </script> - 修改
templates/article.tpl,判斷是否有登入,若有則引入工具列樣板<article class="my-4"> ...略... <div class="row g-0 my-2"> <div class="col-10 bg-light p-2"> {if isset($smarty.session.is_admin) && $smarty.session.is_admin} {include file="toolbar.tpl"} {/if} {$date} @ {$school} 已有 {$count} 次點閱 </div> <div class="col-2 bg-dark bg-opacity-50 p-2 text-white text-center"> {$author} 報導 </div> </div> ...略... </article> - 若是出現錯誤訊息,一樣可以將訊息貼給AI,請他解決,例如:
執行後會出現以下錯誤訊息,該如何修改? Fatal error: Uncaught --> Smarty Compiler: Syntax error in template "file:toolbar.tpl" on line 24 "window.location.href = `admin.php?op=delete&id=${id}`;" unknown tag 'id' <-- thrown in C:\UniServerZ\www\php8\templates\toolbar.tpl on line 24 - 他就會說明原因,並立即修正。像上面是在 Smarty 模板中使用了 JavaScript 的模板字符串語法(像這樣:
${id}),而 Smarty 將其誤解為自己的變數標記,因此錯誤。所以,AI提出解決方案,只要對 JavaScript 進行一些調整就行了:window.location.href = 'admin.php?op=delete&id=' + id; - 如此就大功告成囉!

8-2 製作登入、登出功能