[英]How do you access values injected into HTML templates using JavaScript?
I have an HTML template with a div that looks like this: 我有一个带有div的HTML模板,如下所示:
<div id="some_{{model.property}}_{{other.value}}_text"></div>
I want to use JavaScript in my backbone view to dynamically format those injected values so that the IDs don't have spaces and slashes, etc. problem is that I don't know the right syntax to grab them. 我想在主干视图中使用JavaScript来动态格式化那些注入的值,以使ID不包含空格和斜杠等。问题是我不知道正确的语法来获取它们。 Right now I am doing this:
现在我正在这样做:
var unformatted = "some_{{model.property}}_{{other.value}}_text"
And then using jquery to set the id to a formatted value: 然后使用jquery将id设置为格式化值:
$('.common-class').attr('id', unformatted.formatMe());
It is, of course, giving me the literal string value with the curly brackets and path to the data. 当然,它是给我文字字符串值,并带有大括号和数据路径。 How can I get to the values instead?
我该如何获取这些值? I am using backbone, marionette, require, bootstrap, and Spring with JSPs on the backend.
我在后端使用带有JSP的主干,牵线木偶,require,bootstrap和Spring。 Thanks a lot!
非常感谢!
@meagar is correct. @meagar是正确的。 You should create the properties that you want before rendering the template.
您应该在呈现模板之前创建所需的属性。 The template should reference the new value and not the original model property.
模板应引用新值,而不是原始模型属性。
<div id="{{newValue}}"></div>
If, for example, you want to modify or change someProperty
so that it is rendered as newValue
, you could simply add newValue
as an additional model property. 例如,如果要修改或更改
someProperty
使其呈现为newValue
,则可以简单地将newValue
添加为其他模型属性。
render: function() {
this.model.set('newValue', computeNewValue(someProperty));
this.$el.html(this.template(this.model.toJSON()))
}
If you don't want the newValue
attribute polluting your model, you can simply add it to the object passed to the template: 如果您不希望
newValue
属性污染您的模型,则可以将其添加到传递给模板的对象中:
render: function() {
this.$el.html(this.template(
_(this.model.toJSON()).extend({
newValue: computeNewValue(someProperty)
})
));
}
In the latter case, the model itself isn't modified, but the template is able to access the computed value. 在后一种情况下,模型本身不会被修改,但是模板能够访问计算出的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.