這篇筆記介紹兩個在範本中可用的範本標籤{{if}}  {{html}}

{{if}}可以依資料值產生不同的結果,記得要以{{/if}}結尾,其中還可加入{{else}}分支。

一般而言,${資料物件屬性名}傳回的結果會經過HtmlEncode轉碼,例如,若data.prop1 = “<b>Bold</b>”,<div>${prop1}</div>產出結果將會是<div>&lt;b&gt;Bold&lt;/b&gt;</div>;若想產出<div><b>Bold</b></div>,則要寫成{{html prop1}}。

很簡單吧? 程式範例也很簡單:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Templates Lab 4 - 範本Tag {{html}}</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.js" 
        type="text/javascript"></script> 
    <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"
        type="text/javascript"></script>
    <!--
        {{html}}可以將資料值視為原始HTML標籤
        {{if}}, {{else}}可以依資料值套用不同的區塊
    -->
    <script type="text/x-jquery-tmpl" id="tmplItem">
        <tr><td>${No}</td><td>{{html Name}}</td><td>
            <span {{if Score < 60}}style="background-color:red;color:yellow"{{/if}}>
           ${Score}
            </span>
        </td></tr>
    </script>
    <script type="text/javascript">
        $(function () {
            var data = [
                { No: 1, Name: "Jeffrey", Score: 59 },
                { No: 2, Name: "<b>Darkthread</b>", Score: 75 },
                { No: 3, Name: "<span style='color:red'>Linda</span>", Score: 96 }
            ];
 
            //將結果附加到DOM顯示出來
            $("#tmplItem").tmpl(data).appendTo("#tb");
        });
    </script>
</head>
<body>
<table><tbody id="tb"></tbody></table>
</body>
</html>


Comments

Be the first to post a comment

Post a comment