Use attributes with weird chars in Marionette / underscore template

♀尐吖头ヾ 提交于 2019-12-11 18:23:32

问题


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: Unexpected token ILLEGAL

Using the syntax ['@id'] does not produce the expected result.

Do I have to override the serializeData function?

Thanks


回答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.



来源:https://stackoverflow.com/questions/13096106/use-attributes-with-weird-chars-in-marionette-underscore-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!