开发者

How can I access variables of an outer scope from within an {{each}} block of a jQuery tmpl template?

开发者 https://www.devze.com 2023-01-28 07:40 出处:网络
For example, in this code: <div id=\"user_collection_requests-${id} table-cell\" class=\"user_collection_requests\">

For example, in this code:

<div id="user_collection_requests-${id} table-cell" class="user_collection_requests">
        {{if requests}}
            {{each(i, user) requests}}
                <div id="user_collection_request-${id}-${user.id}" ...
            {{/each}}
        {{/if}}
    </div>

The first ${id} prints the outer object's id attrib开发者_运维百科ute, but the second ${id} prints the same as ${user.id}. I want to grab the outer scope's id from within the {{each}} block.

Is this possible? Or do I have to be sure to name the variables so that a collision like this will not occur?


You can declare a variable outside your {{each}} block

${( $data.localVariable = $id ),''}

and access it inside later

${localVariable}


<script id="template" type="text/x-jquery-tmpl">
    <div id="user_collection_requests-${id} table-cell" class="user_collection_requests">
        {{if user}}
            {{each user}}
                <div id="user_collection_request-${$data.id}-${id}"></div>
            {{/each}}
        {{/if}}
    </div>    
</script>

Example: http://jsfiddle.net/P4jGt/


In simple words

use ${( $data.UserId = Id ),''} and later use that inside each as UserId

Here is my code which I am using in one of the scripts

<script id="templateFolderTop" type="text/html">
    <li>
        ${( $data.ParentTagSlug = Tag.replace(/[^a-zA-Z0-9_]/g,'-') ),''}
        <span class="CAPS">
            <a id="${ParentTagSlug}" onclick="_NewsManager.FolderSubCall(${Id})"></a>
            <a href="#${ParentTagSlug}" class="top_menu_href" >${Tag}</a>
        </span>
        {{if ChildList.length}}
        ${( $data.ParentTag = ParentTagSlug ),''}
        <div class="dropdown_2columns">
            <div class="col_1 firstcolumn">
                <ul>
                    {{each ChildList}}
                    ${( $data.TagSlug = Tag.replace(/[^a-zA-Z0-9_]/g,'-') ),''}
                    <li>
                        <a id="${ParentTag}-${TagSlug}" onclick="_NewsManager.NewsListCall(${Id})"></a>
                        <a href="#${ParentTag}-${TagSlug}" >${Tag}</a>
                    </li>
                    {{/each}}
                </ul>
            </div>
        </div>
        {{/if}}
    </li>
</script>


You need to use jquery's parent method

http://api.jquery.com/parent/

.parent() gives you the parents property's

0

精彩评论

暂无评论...
验证码 换一张
取 消