Reputation: 3
this should be easy or simple, but I donot know why it doesnot work. I waste here about 1 whole day.
https://jsfiddle.net/panyongfeng/m73vnz9j/
<script>
var tpl = "hello: <%= name %>";
var compiled = _.template(tpl);
compiled({
name: "dadf"
});
alert(compiled());
</script>
I just get "hello result", which should be hello dadf. Would you please point out what's wrong? thanks
Upvotes: 0
Views: 1012
Reputation: 994
Your code is right but if you want to use the result then you need to store the result of compiled method. So your code should be -
var dump = compiled({ name: "dadf" });
alert(dump);
Upvotes: 0
Reputation: 434665
You're misunderstanding the examples in the documentation. When they say this:
var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"
The context is that they're working inside a REPL as though they ran node
from the command line. That means that the stuff after =>
is the result of the last expression and the hello: moe
string is what compiled({name: 'moe'})
returns. Running the template function returns the filled in template as a string, it doesn't stash the results anywhere.
You want to drop the last alert
call in favor of this:
alert(compiled({ name: "dadf" }));
Upvotes: 1