About hogan.js

About 

Hogan.js is a JavaScript templating engine for Mustache templates.

Hogan is a JavaScript library that parses and compiles Mustache templates. It can run in both the web browser and other JavaScript engines such as Node.js and Rhino.

Example usage

Hogan uses standard mustache templates:

<script type="text/html" id="topUsersTemplate">
    <h1>{{title}}</h1>
    <ul>
        {{#users}}
            <li>{{name}} ({{postCount}})</li>
        {{/users}}
    </ul>
</script>

These can then be compiled on the client:

var template = Hogan.compile(document.getElementById("topUsersTemplate").innerHTML);

Or pre-compiled on the server and delivered as pure JavaScript code, which can just be included with a script tag. This is preferable as compilation is the most expensive operation:

<script src="/js/topUsersTemplate.js"></script>

The template is then rendered with a context object which contains the fields to expand the template.

var context = {
    "title": "Top Users",
    "users": [
        {
            "name": "User 1",
            "postCount": 2000
        },
        {
            "name": "User 2",
            "postCount": 1900
        },
        {
            "name": "User 3",
            "postCount": 1800
        }
    ]
};

document.body.innerHTML = template.render(context);

The preceding code would produce:

<h1>Top Users</h1>
<ul>
    <li>User 1 (2000)</li>
    <li>User 2 (1900)</li>
    <li>User 3 (1800)</li>
</ul>
history  excerpt history
posted @ 2017-02-19 18:08  goldenstones  阅读(167)  评论(0编辑  收藏  举报