defining new variable within jquery template
Asked Answered
M

3

16

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

Mohair answered 20/2, 2011 at 11:20 Comment(1)
Your question was a good answer :)Likable
V
21

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/

Virgel answered 20/2, 2011 at 21:21 Comment(1)
And for setting variables perhaps $.extend($.tmpl.tag, {"setvar": {open: "$1;"}});Misdo
A
2

You can extend jquery template with eval tag

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

and use

{{eval var xxx = 123}}
{{eval xxx += 23}}
Arrogance answered 18/10, 2011 at 8:57 Comment(0)
V
1

I do:

${xxx=13, ""}

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

Vaal answered 3/7, 2013 at 15:32 Comment(1)
jquery.tmpl creates these variables in global context. xxx will be global variable.Insecurity

© 2022 - 2024 — McMap. All rights reserved.