Skip to content Skip to sidebar Skip to footer

Use Attributes With Weird Chars In Marionette / Underscore Template

I have a model with attributes names like @id, @type, etc. If I try to use <%= @id %> in a Marionette.ItemView template (with Underscore) I get Uncaught SyntaxError: Unexpe

Solution 1:

Underscore templates require JavaScript expressions inside <%= ... %>, the compiled template uses with so you can usually reference object properties as though they were variables. Your problem is that @id is not a valid JavaScript expression.

So yes, providing your own serializeData to remove the @s is probably your best bet. Another possibility would be to use the variable option with _.template:

By default, template places the values from your data in the local scope via the with statement. However, you can specify a single variable name with the variable setting. This can significantly improve the speed at which a template is able to render.

_.template("Using 'with': <%= data.answer %>", {answer:'no'}, {variable:'data'});
=> "Using 'with': no"

Then you could use things like <%= data['@id'] %>; the problem is that getting this approach to work with Marionette might be more work than simply cleaning up the @s in a custom serializeData method.

Post a Comment for "Use Attributes With Weird Chars In Marionette / Underscore Template"