How to handle an IF STATEMENT in a Mustache template?

前端 未结 4 1537
一个人的身影
一个人的身影 2020-12-13 23:34

I\'m using mustache. I\'m generating a list of notifications. A notification JSON object looks like:

[{\"id\":1364,\"read\":true,\"author_id\":30,\"author_na         


        
4条回答
  •  半阙折子戏
    2020-12-14 00:36

    I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :

    function buildOptions (object) {
        var validTypes = ['string', 'number', 'boolean'];
        var value;
        var key;
        for (key in object) {
            value = object[key];
            if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
                object[key + '=' + value] = true;
            }
        }
        return object;
    }
    

    With this hack, an object like this:

    var contact = {
      "id": 1364,
      "author_name": "Mr Nobody",
      "notified_type": "friendship",
      "action": "create"
    };
    

    Will look like this before transformation:

    var contact = {
      "id": 1364,
      "id=1364": true,
      "author_name": "Mr Nobody",
      "author_name=Mr Nobody": true,
      "notified_type": "friendship",
      "notified_type=friendship": true,
      "action": "create",
      "action=create": true
    };
    

    And your mustache template will look like this:

    {{#notified_type=friendship}}
        friendship…
    {{/notified_type=friendship}}
    
    {{#notified_type=invite}}
        invite…
    {{/notified_type=invite}}
    

提交回复
热议问题