3

According to underscore's documentation, it allows you to do string template/interpolation like below:

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
// => "hello: moe"

Instead of using variable symbol like "name", I wonder if there is any way to use integer as the key? For example:

var compiled = _.template("hello: <%= 1 %>");
compiled({"1": 'moe'});
// => "hello: moe"

I gave it a try but underscorejs template evaluates it as a literal instead of variable, is there any way to do templating with underscore if the provided variable contains such integer key in it? Thanks.

1 Answer 1

2

No, you can not use an integer, you have to use a valid variable name, this means it can have an integer but it can not be only an integer.

Things that work are:

compiled = _.template("hello: <%= a1 %>");
console.log(compiled({a1: 'moe'}));

compiled = _.template("hello: <%= _1 %>");
console.log(compiled({_1: 'moe'}));


compiled = _.template("hello: <%= a %>");
console.log(compiled({a: 'moe'}));

http://jsfiddle.net/BwHxv/309/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.