2

Dojo用文本lang.replace()替换未定义的占位符。undefined是否可以在占位符中定义默认值?

假设我想要以下占位符:

<div class="message">The query returned {result.rows:0} rows</div>

占位符将替换为返回的行数,但当变量rows不可用时(例如,结果包含错误消息),它将替换为 0。

4

1 回答 1

3

There are two approaches you can consider. The first is to mixin the results object with defaults before passing it into the replace function.

var defaults = {
    rows: 0
};
var data = lang.mixin(lang.clone(defaults), result);

lang.replace(template, data);

The second approach is instead of passing a data object, pass a function that knows how to default the value when missing.

http://dojotoolkit.org/reference-guide/1.9/dojo/_base/lang.html#with-a-function

于 2013-07-04T14:38:06.250 回答