Conditionals in jQuery templates

杀马特。学长 韩版系。学妹 提交于 2020-01-04 03:59:06

问题


I have a jquery template setup like this:

<script id='tmpl-video_list' type='text/x-jquery-tmpl'>
<li>
    <a href='${url}'><br/>
        <span class='image_border'>
            <span class='image_container'>
                <img src='${thumb}' alt='' title='' />
            </span>
        </span>
    </a>
    <div class='search_block'>
        <span class='name'>${caster_name}</span>
            <a href='${url}'>
                <span class='search_title'>${title}</span>
            </a>
    </div>
</li>

And the data I'm sending looks something like this:

{
    _index:i,
    url: url,
    thumb: thumb,
    name: name,
    title: title
}

All That is working great. My question is that if there is a way to put a conditional in there. I know about the {{if}} and such as stated in the docs but I'm wondering if you can do something like this:

{{if ${_index}+1 % 5 == 0}} class='last_search_video' {{/if}}

I tried that and it didn't work. I actually don't like the _index in my object but I thought I'd give that a change. I'm thinking the current index is passed into the loop for the template but I have no idea.

I'm not married to jQuery's templating plugin so if someone knows a better plugin please feel free to suggest another one.


回答1:


I actually don't like the _index in my object

Good news! You don't actually need it. Adapting this excellent question and answer to your problem, you need to do a few things to make finding the index of the current item you're rendering easier:

  1. Add a function in the options parameter to .tmpl() that you can use to retrieve the index of the current item:

    $("#tmpl-video_list").tmpl(data, {
        getIndex: function(item) {
            return $.inArray(item, data);
        } 
    });
    
  2. Modify your template to make use of that function:

    <script id='tmpl-video_list' type='text/x-jquery-tmpl'>
        <li {{if $item.getIndex($item.data) + 1 % 5 === 0 }} class='last_search_video' {{/if}}>
            <!-- etc., etc., -->
        </li>
    </script>
    

Here's a simplified working sample: http://jsfiddle.net/gsd6D/




回答2:


You don't have to "templatize" the _index property in the {{if}}. You can just write

{{if (_index + 1) % 5 == 0}} class='last_search_video' {{/if}}


来源:https://stackoverflow.com/questions/6528484/conditionals-in-jquery-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!