weex-templater
Version:
Weex <template> transformer
70 lines (66 loc) • 1.59 kB
JavaScript
var tagSource = '{{{(.+?)}}}|{{(.+?)}}'
var tagRE = new RegExp(tagSource, 'g')
var expRE = new RegExp(tagSource)
var htmlRE = new RegExp('^{{{.*}}}$')
/**
* Parse a template text string into an array of tokens.
*
* @param {String} text
* @return {Array<Object> | null}
* - {String} type
* - {String} value
* - {Boolean} [html]
* - {Boolean} [oneTime]
*/
function parseText(text) {
text = text.replace(/\n/g, '')
/* istanbul ignore if */
if (!tagRE.test(text)) {
return null
}
var tokens = []
var lastIndex = tagRE.lastIndex = 0
var match, index, html, value, first, oneTime
/* eslint-disable no-cond-assign */
while (match = tagRE.exec(text)) {
/* eslint-enable no-cond-assign */
index = match.index
// push text token
if (index > lastIndex) {
tokens.push({
value: text.slice(lastIndex, index)
})
}
// tag token
html = htmlRE.test(match[0])
value = html ? match[1] : match[2]
first = value.charCodeAt(0)
oneTime = first === 42 // *
value = oneTime
? value.slice(1)
: value
tokens.push({
tag: true,
value: value.trim(),
html: html,
oneTime: oneTime
})
lastIndex = index + match[0].length
}
if (lastIndex < text.length) {
tokens.push({
value: text.slice(lastIndex)
})
}
return tokens
}
/**
* judge expression
* @param {String} text
* @return {Boolean}
*/
function isExpr(text) {
return expRE.test(text)
}
exports.parseText = parseText
exports.isExpr = isExpr