Last active
May 16, 2022 00:19
-
-
Save imryanjay/1d91b2c9f768af7c1b1877a51a4a75f0 to your computer and use it in GitHub Desktop.
Function to get handlebar values from a template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
export const getHBValues = (text) => { | |
const re = /{{[{]?(.*?)[}]?}}/g; | |
const tags = []; | |
let matches; | |
while (Boolean((matches = re.exec(text)))) { | |
if (matches) { | |
tags.push(matches[1]); | |
} | |
} | |
const root = {}; | |
let context = root; | |
const stack = []; | |
const setVar = (variable, val) => { | |
// Dot Notation Breakdown | |
if (variable.match(/\.*\./) && !variable.match(/\s/)) { | |
let notation = variable.split('.') | |
_.set(context, notation, "") | |
} | |
else { | |
context[variable.trim()] = val; | |
} | |
}; | |
for (let tag of tags) { | |
if (tag.startsWith('! ')) { | |
continue; | |
} | |
if (tag == 'else') { | |
continue; | |
} | |
if ('#^'.includes(tag[0]) && !tag.includes(' ')) { | |
setVar(tag.substr(1), true); | |
stack.push(context); | |
continue; | |
} | |
if (tag.startsWith('#if')) { | |
const vars = tag.split(' ').slice(1); | |
for (const v of vars) { | |
setVar(v, true); | |
} | |
stack.push(context); | |
continue; | |
} | |
if (tag.startsWith('/if')) { | |
context = stack.pop(); | |
continue; | |
} | |
if (tag.startsWith('#with ')) { | |
const v = tag.split(' ')[1]; | |
let newContext = {}; | |
context[v] = newContext; | |
stack.push(context); | |
context = newContext; | |
continue; | |
} | |
if (tag.startsWith('/with')) { | |
context = stack.pop(); | |
continue; | |
} | |
if (tag.startsWith('#unless ')) { | |
const v = tag.split(' ')[1]; | |
setVar(v, true); | |
stack.push(context); | |
continue; | |
} | |
if (tag.startsWith('/unless')) { | |
context = stack.pop(); | |
continue; | |
} | |
if (tag.startsWith('#each ')) { | |
const v = tag.split(' ')[1]; | |
const newContext = {}; | |
context[v] = [newContext]; | |
stack.push(context); | |
context = newContext; | |
continue; | |
} | |
if (tag.startsWith('/each')) { | |
context = stack.pop(); | |
continue; | |
} | |
if (tag.startsWith('/')) { | |
context = stack.pop(); | |
continue; | |
} | |
setVar(tag, ''); | |
} | |
return root; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm curious why this script returns
root
instead ofObject.keys(root)
🤔