diff --git a/index.js b/index.js index 66b473a..de94abb 100644 --- a/index.js +++ b/index.js @@ -6,27 +6,63 @@ exports.printVersion = () => { exports.compile = (template, input) => { let index = 0 + const getValue = (tagContent) => { + console.log('input', tagContent) + let tagContentSplit = tagContent.split('.') + let varLevel = null + tagContentSplit.forEach( (level) => { + const isIndex = Number.isInteger(parseInt(level)) + if(!varLevel) varLevel = input + varLevel = isIndex ? varLevel[parseInt(level)] : varLevel[level] + }) + return typeof varLevel === 'string' ? varLevel.trim() : varLevel + } + while(index < template.length) { - const nextOpen = template.indexOf('{{', index + 1) + const nextOpen = template.indexOf('{{', index+1) + if(nextOpen == index || nextOpen == -1) { index = template.length } else { index = nextOpen - const nextClose = template.indexOf('}}', index + 1) + const nextClose = template.indexOf('}}', index+1) if(nextClose == index || nextClose == -1) { index = template.length } else { index = nextOpen+2 - const tagContent = template.substring(nextOpen+2, nextClose) - const tagContentSplit = tagContent.split('.') - let varLevel = input - tagContentSplit.forEach( (level) => { - const isIndex = Number.isInteger(parseInt(level)) - varLevel = isIndex ? varLevel[parseInt(level)] : varLevel[level] - }) - template = template.replace(tagContent, varLevel) + let tagContent = template.substring(nextOpen+2, nextClose) + + if(tagContent.substring(0,1) == '#') { + const isIf = tagContent.substring(0,3) == '#if' + const isUnless = tagContent.substring(0,7) == '#unless' + + console.log('tagContent.substring(0,3)',tagContent.substring(0,3),index) + if(isIf) { + const conditionStart = template.indexOf('}}', index+1) + const conditionStop = template.indexOf('{{/if}}', conditionStart+1) + const conditionContent = template.substring(conditionStart+2, conditionStop) + const conditionFull = template.substring(index-2, conditionStop+7) + const value = getValue(tagContent.substring(4)) ? conditionContent : '' + template = template.replace(conditionFull, value) + console.log('conditionFull',conditionFull, `-${value}-`, `-${tagContent.substring(4)}-`, conditionContent) + index += value.length + } else if(isUnless) { + const conditionStart = template.indexOf('}}', index+1) + const conditionStop = template.indexOf('{{/unless}}', conditionStart+1) + const conditionContent = template.substring(conditionStart+2, conditionStop) + const conditionFull = template.substring(index-2, conditionStop+11) + const value = !getValue(tagContent.substring(8)) ? conditionContent : '' + template = template.replace(conditionFull, value) + index += value.length + } + console.log('index', index) + } else { + const value = getValue(tagContent) + template = template.replace(`{{${tagContent}}}`, value) + //index += value.length+1 + } } } } - console.log(template) + return template }