If I feed underscore template with an object like
{
key1: value1,
key2: [value20, value21, ...]
}
then in template I can iterate over it using _.each(key2, function())
.
But can I iterate through the array if it is top-level like
[
val1,
val2,
...
]
May be something like _.each(this, function())
It seems you're looking for _.values .
var data = {
key1: "value1",
key2: ["value20","value21"]
};
console.log(_.values(data));
//["value1", ["value20", "value21"]]
Then you can do _.each on it to iterate through the list
Yes. By default, the object passed into the template is named obj
. lodash additionally allows this to be renamed using the variable
property of the options
argument passed in; I don't believe underscore supports this.
Demonstrating from the REPL:
> require('underscore').template('<%= obj.length %>')([ 'a', 'b', 'c' ]);
'3'
> require('underscore').template('<%= foo.length %>', { variable: 'foo' })([ 'a', 'b', 'c' ]);
ReferenceError: foo is not defined
> require('lodash').template('<%= foo.length %>', { variable: 'foo' })([ 'a', 'b', 'c' ]);
'3'
My source is the lodash docs ; I skimmed through the underscore docs and didn't see a reference to this, so it may be unsupported functionality in underscore.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.