@alicd/templateparser
Version:
walle template parser
115 lines (106 loc) • 3.35 kB
JavaScript
/**
* @license
* Copyright Alibaba Group and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import config from '../config';
import express from './express';
const tagStartReplaceRegExp = new RegExp(config.tagStartReplaceStr, 'g');
const tagEndReplaceRegExp = new RegExp(config.tagEndReplaceStr, 'g');
const compsRegexp = new RegExp('(<\\/?[\\w]+[^<>]*[\\/]?>)');
export default (str, runtimeOn) => {
if (!str) {
return null;
}
str = str
.replace(/\ /g, ' ')
.replace(/\ /g, ' ')
.replace(/\</g, '<')
.replace(/\>/g, '>')
.replace(/\&/g, '&')
.replace(/\"/g, '\'')
.replace(tagStartReplaceRegExp, '<')
.replace(tagEndReplaceRegExp, '>');
// walle syntax: with `{}` syntax
if (express.test(str)) {
// tpl component.
if (compsRegexp.test(str)) {
str = express.filter(str);
try {
// handle the template in attributes of the node.
if (!runtimeOn) {
// `__walle_h__` alias of walle.h
// `__walleTPSplitHolder__` walle's split holder
return new Function(
'return __walle_h__(`__walleTPSplitHolder__' +
str +
'__walleTPSplitHolder__`, this)'
);
}
// use for runtime.
else {
str = str.replace(/"/g, '\\"').replace(/'/g, '\\\'');
return new Function(`return walle.createEle('${str}', this)`);
}
} catch (e) {
console.error(
'\x1B[31m%s\x1b[0m',
`Syntax error on analysis express: \`${str}\` \n `,
e
);
return new Function(`
console.error(
\`Syntax error on analysis express: \\\`${str}\\\` \\n ${e.toString()}\`
);
`);
}
}
// express.
else {
// express filter.
str = express.filter(str);
// handle es6 syntax for the runtime case.
if (runtimeOn) {
// arrow function.
const arrowFnParts = str.split('=>');
if (arrowFnParts.length > 1) {
arrowFnParts[0] = arrowFnParts[0].trim().replace(/[\(|\)]*/gm, '');
arrowFnParts[1] = arrowFnParts[1]
.trim()
.replace(/^{/gm, '')
.replace(/}$/gm, '');
str = `(function ( ${arrowFnParts[0]} ) { ${arrowFnParts[1]} } ).bind(this)`;
}
}
// output function.
try {
let functionTemplate;
if (!runtimeOn) {
// alias: `if(__walleTPReplaceHolder__` => `with(`
functionTemplate = `if(__walleTPReplaceHolder____walle_c__){return ${str}}`;
}
// use for runtime.
else {
// alias: `if(__walleTPReplaceHolder__` => `with(`
functionTemplate = `with(__walle_c__){return ${str}}`;
}
return new Function('__walle_c__', functionTemplate);
} catch (e) {
console.error(
'\x1B[31m%s\x1b[0m',
`Syntax error on analysis express: \`${str}\` \n `,
e
);
return new Function(`
console.error(
\`Syntax error on analysis express: \\\`${str}\\\` \\n ${e.toString()}\`
);
`);
}
}
} else {
return str;
}
};