Wednesday, 4 September 2013

Rendering from variable html using jquery template

I started to use template for rendering my code from json responses.
Everything work great if you do not have html in the variables.

Supposed documentation should be here: http://api.jquery.com/category/plugins/templates

I could not find it.

Modifying example from github:

I have found example how to achieve this here.

I have not been able to make this work.
Finally I have  found out that the correct syntax is:


${Name} =>{{html Name}}
 Note that there is no longer: $.

Source for this example:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-2.0.3.js"></script>
    <script src="Scripts/jQuery.tmpl.js"></script>
    <style>
        table { border-collapse:collapse; margin:8px; background-color:#f8f8f8; }
        table td { border:1px solid blue; padding:3px; }
    </style>
    <script type="text/javascript">
        $(document).ready(function() {

            var movies = [
                { Name: "The Red Violin<strong>test</strong>", ReleaseYear: "1998", Director: "Fran├žois Girard" },
                { Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
                { Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
            ];

            var markup = "<tr><td colspan='2'>{{html Name}}</td><td>Released: ${ReleaseYear}</td><td>Director: ${Director}</td></tr>";

            /* Compile markup string as a named template */
            $.template("movieTemplate", markup);

            /* Render the named template */
            $("#showBtn").click(function () {
                $("#movieList").empty();
                $.tmpl("movieTemplate", movies).appendTo("#movieList");
            });
        });
       

    </script>
</head>
    <body>
       
        <button id="showBtn">Show movies</button><br/>
        <table><tbody id="movieList"></tbody></table>

    </body>
</html>