jQuery Nested Templates using options parameter

2019-07-30 14:50发布

问题:

I don't understand how to reference the options parameter in nested templates.

Please see:

<div id="myContainer"></div>
<script type="text/javascript">
    var tmplMain = "<div><span>${title}</span>" + 
                   "<p style=\"border: solid 1px #f00\">${$item.details}</p>" +
                   "{{tmpl \"nestedTemplate\"}}</div>";

    var tmplNested = "<p style=\"border: solid 1px #0f0\">${$item.details}</p>";

    var _mainTemplate = jQuery.template("mainTemplate", tmplMain);
    jQuery.template("nestedTemplate", tmplNested);

    var _data = {title: "My Title"};
    var _options = {details: "My Details};

    jQuery.tmpl(_mainTemplate, _data, _options).appendTo("#myContainer");
</script>

Which will output this: http://i.stack.imgur.com/r7A7g.jpg

So either I'm not referencing "${$item.details}" correctly in the nested template or I'm not passing the options correctly in the {{ tmpl }} tag. I'm stumped.

回答1:

You would need to pass any options that you want to the {{tmpl}} tag. Something like:

{{tmpl($data, { details: $item.details}) "nestedTemplate" }}

You could even just pass $item for the options to the nested template, but $item has more than just your options on it.

Sample here: http://jsfiddle.net/rniemeyer/Xzgpr/