萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET MVC 使用 jQuery 模板引擎 jTemplates 渲染表格完整實作

為什麼需要前端模板引擎?

在 ASP.NET MVC 中,Controller 回傳 JSON 資料,前端需動態產生複雜 HTML 表格。傳統字串拼接方式:

  • 程式碼難維護,HTML 與 JS 混雜
  • 易產生 XSS 漏洞 (未正確編碼)
  • 巢狀結構 (如主從表) 處理痛苦

jTemplates (jQuery Templates 前身) 提供宣告式模板語法,分離資料與呈現邏輯。

完整前端實作 (Index.cshtml)


@{
    Layout = null;
}



    jTemplates 表格渲染示範
    
    
    
    


    

後端 Controller 實作


public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    /// 
    /// 回傳 JSON 資料供 jTemplates 渲染
    /// 
    public JsonResult TempleteData()
    {
        var userList = new List
        {
            new UserEntity 
            { 
                UserName = "Tina", 
                PassportID = 23433, 
                Email = "tina@example.com", 
                Password = "NKASD", 
                Url = "https://www.example.com" 
            },
            new UserEntity 
            { 
                UserName = "Lucy", 
                PassportID = 3444, 
                Email = "lucy@example.com", 
                Password = "v23sda", 
                Url = "https://www.qq.com" 
            }
        };

        return Json(userList);
    }
}

public class UserEntity
{
    public string UserName { get; set; }
    public int PassportID { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string Url { get; set; }
}

jTemplates 核心語法解析

語法說明範例
{#template NAME}定義模板區塊{#template MAIN}...{#/template MAIN}
{#foreach $T as item}迴圈陣列 $T (根資料){#foreach $T as uu}...{#/for}
{#include SUB root=$T.item}引用子模板,傳入子物件{#include ROW root=$T.uu}
{$T.Property}輸出屬性值 (自動 HTML 編碼){$T.UserName}
{$T.Property.method()}呼叫字串方法{$T.UserName.bold()}
{$T.Url.link($T.Url)}內建 link() 產生 <a> 標籤產生超連結
{#cycle values=['odd','even']}輪替輸出 (斑馬紋)class="{#cycle values=['','evenRow']}"
{#if condition}...{#/if}條件判斷{#if $T.IsActive}啟用{#/if}
{#else}...{#/else}否則分支{#else}停用{#/else}

關鍵技術細節

1. 模板隔離:`type="text/html"`

瀏覽器不會解析此類型的 ` // 渲染 $("#container").html($("#userTemplate").render(userList));

Vue.js / React / Blazor (元件化框架)

對於複雜互動應用,採用元件化框架比模板引擎更具擴展性。

總結

jTemplates 在 ASP.NET MVC 早期提供了優雅的「資料與呈現分離」方案:Controller 專注回傳 JSON,View 專注宣告式模板渲染。雖然已非主流選擇,但其設計理念 (模板隔離、子模板組合、內建格式化) 仍具參考價值。現代專案建議遷移至 jsRender 或採用 Vue/React/Blazor 等元件化框架。

copyright © 萬盛學電腦網 all rights reserved