扩充 tpl filter 的 filter 指定 并 补充文档

This commit is contained in:
liaoxuezhi 2019-10-29 18:38:26 +08:00
parent 722a32c64b
commit 4b7c3af47f
2 changed files with 22 additions and 12 deletions

View File

@ -94,6 +94,7 @@ tpl 类型的渲染器支持用 JS 模板引擎来组织输出,采用的 lodas
- `upperCase` 转大写 - `upperCase` 转大写
- `base64Encode` base64 转码 - `base64Encode` base64 转码
- `base64Decode` base64 解码 - `base64Decode` base64 解码
- `filter` 过滤数组,操作对象为数组,当目标对象不是数组时将无效。使用语法 ${xxx | filter: 参与过滤的字段集合:指令:取值变量名}。比如: `${xxx|filter:readonly:isTrue}` 将xxx 数组中 readonly 为 true 的成员提取出来。再来个栗子:`${xxx|filter:a,b:match:keywords}` 将 xxx 数组中成员变量 a 或者 b 的值与环境中 keywords 的值相匹配的提取出来。如果不需要取变量,也可以写固定值如:`${xxx|filter:a,b:match:'123'}`
组合使用。 组合使用。

View File

@ -212,22 +212,31 @@ export const filters: {
return input ? filterDate(input, this, inputFormat).format(outputFormat) : ''; return input ? filterDate(input, this, inputFormat).format(outputFormat) : '';
}, },
asArray: input => (input ? [input] : input), asArray: input => (input ? [input] : input),
filter: function(input, keys, exp) { filter: function(input, keys, expOrDirective, arg1) {
let keywords: string; if (!Array.isArray(input) || !keys || !expOrDirective) {
if (!Array.isArray(input) || !keys || !exp || !(keywords = resolveVariable(exp, this as any))) {
return input; return input;
} }
keywords = keywords.toLowerCase(); let directive = expOrDirective;
let fn: (value: any, key: string, item: any) => boolean = () => true;
if (directive === 'isTrue') {
fn = value => !!value;
} else if (directive === 'isFalse') {
fn = value => !value;
} else if (directive === 'isExists') {
fn = value => typeof value !== 'undefined';
} else {
if (directive !== 'match') {
directive = 'match';
arg1 = expOrDirective;
}
arg1 = arg1 ? (/^('|")(.*)\1$/.test(arg1) ? RegExp.$2 : resolveVariable(arg1, this as any)) : '';
fn = value => !!~String(value.toLowerCase()).indexOf(arg1);
}
keys = keys.split(/\s*,\s*/); keys = keys.split(/\s*,\s*/);
return input.filter((item: any) => return input.filter((item: any) => keys.some((key: string) => fn(resolveVariable(key, item), key, item)));
keys.some(
(key: string) =>
~String(resolveVariable(key, item))
.toLowerCase()
.indexOf(keywords)
)
);
}, },
base64Encode(str) { base64Encode(str) {
return btoa( return btoa(