简体   繁体   English

为什么车把模板中的修剪字符串不呈现?

[英]Why does trimmed string in handlebars template not render?

Can anyone explain why in the following example result prints as [object Object] to the console when typeof result returns string ?谁能解释为什么在下面的示例中,当typeof result返回string时, result会打印为[object Object]到控制台?

I took this example from the very bottom of the handlebars documentation here: https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access我从车把文档的最底部拿了这个例子: https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access

I assume that this may have something to do with the fact that handlebars does not allow access to the toString method of the aString prototype but if the documentation is correct this should work.我认为这可能与车把不允许访问aString原型的toString方法这一事实有关,但如果文档正确,这应该可以工作。

 var template = Handlebars.compile(document.getElementById('template').innerHTML); var result = template({ aString: " abc " }, { allowedProtoMethods: { trim: true } }); console.log(result, typeof result); document.getElementById('output').innerHTML = result;
 <script src="https://unpkg.com/handlebars@latest/dist/handlebars.js"></script> <div id="output"></div> <script type="template/handlebars" id="template">{{aString.trim}}</script>

This is essentially a typical "losing this " problem.这本质上是一个典型的“丢this ”问题。 When handlebars evaluates aString.trim , it gets back a reference to String.prototype.trim .当车把评估aString.trim时,它会返回对String.prototype.trim的引用。 At this point the "connection" to aString is lost and trim doesn't know on which value to operate on.此时,与aString的“连接”丢失,并且trim不知道要对哪个值进行操作。

This can be demonstrated by replicating this with a custom object + methods:这可以通过使用自定义 object + 方法复制它来证明:

 var template = Handlebars.compile(document.getElementById('template').innerHTML); var result = template({ foo: { data: "data", getData() { return this.data || 'not found'}, staticData() { return 'static data'; } }, }); document.getElementById('output').innerHTML = result;
 <script src="https://unpkg.com/handlebars@latest/dist/handlebars.js"></script> <div id="output"></div> <script type="template/handlebars" id="template">{{foo.getData}} {{foo.staticData}}</script>

See how it renders not found instead of data ?看看它如何呈现not found而不是data That's because this refer to the object in foo , it refers to something else (possibly the global object).这是因为this指的是foo中的 object ,它指的是其他东西(可能是全局对象)。

In other words it looks like you cannot call methods that depend on this that way.换句话说,您似乎无法以这种方式调用依赖this的方法。

You could use a helper instead.您可以改用助手

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM