Reputation:
I have a model given by a REST API and one of the name's attributes is like this:
defaults: {
...
"user-name" : "",
...
}
Then when I try to render it in a template by this way:
<script type="text/template" id="list">
<strong>User name: </strong> <%= user-name %>
</script>
I have no problem to render the other attributes, but with this, it only recognise the first part of the name 'user' and consecuently it gives an error. Is there any way to change the name when you render or to escape the symbol '-', so the template recognise it?
Thank you!
Upvotes: 3
Views: 428
Reputation: 35930
You can wrap the data to an additional object and use the bracket indexer syntax. So, instead of:
_.template("<%= user-name %>", {"user-name": "..."} );
You can use:
_.template("<%= model['user-name'] %>", { model: {"user-name": "..." } } );
Upvotes: 2
Reputation: 11383
The -
isn't a valid variable character, so you'll have to change user-name
to something else.
If you can't change the attribute throughout the model, and you're passing the model attributes to the template simply by calling model.toJSON()
, you can change that variable just before passing it to the template:
var attrs = model.toJSON();
// change user-name to something else
attrs.user_name = attrs['user-name'];
// and delete it
delete attrs['user-name'];
// pass attrs to the template like normal
// ...
Upvotes: 2