defining new variable within jquery template

强颜欢笑 提交于 2019-12-03 15:37:13

问题


Is it possible to define a new variable within a jquery template? I read the official jquery template docs but could not find anything on this. I tried something like {{ var xxx=123 }} but it didn't work. Finally I am using a hack by doing

${$item.xxx=123,""}

and later using

$item.xxx

but I am sure it is not the best approach...


回答1:


I don't think that doing the $item approach is too bad. It is consistent with where you would look for variables that are passed in via the options parameter to $.tmpl.

Another approach that I have used, based on a small tip here, is to actually define a "var" template tag.

Just do:

$.extend($.tmpl.tag, {
    "var": {
        open: "var $1;"
    }
});

Then you can use it in your templates like:

{{var xxx=123}}
...
<div>${xxx}</div>

Also, nice blog post here on custom jquery template tags: http://blog.sterkwebwerk.nl/2010/12/15/custom-jquery-template-tags-1/




回答2:


You can extend jquery template with eval tag

$.extend($.tmpl.tag, { "eval": { open: "$1;"} });

and use

{{eval var xxx = 123}}
{{eval xxx += 23}}



回答3:


I do:

${xxx=13, ""}

and then i can use xxx in a sub or in the same template



来源:https://stackoverflow.com/questions/5056679/defining-new-variable-within-jquery-template

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