jQuery模板中的条件 [英] Conditionals in jQuery templates

查看:72
本文介绍了jQuery模板中的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的jquery模板设置:

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
}

一切都很好。我的问题是,如果有办法在那里设置条件。我知道{{if}}和文档中说明的内容,但我想知道你是否可以这样做:

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}}

我试过了,但没效果。我实际上不喜欢我的对象中的 _index ,但我想我会给它一个改变。我认为当前索引被传递到模板的循环但我不知道。

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.

我没有和jQuery的模板插件结婚所以如果有人知道更好的插件请随意建议另一个。

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

推荐答案


我实际上不喜欢我的
对象中的_index

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. 选项中添加一个函数可用于检索当前项目索引的 .tmpl()参数:

  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);
    } 
});


  • 修改模板以使用该功能:

  • 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>
    


  • 这是一个简化的工作样本: http://jsfiddle.net/gsd6D/

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

    这篇关于jQuery模板中的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆