feat: improve evaluation of dynamic content inside {{ }}
- evaluate js expressions - fix regex matching skips every other match
This commit is contained in:
parent
bd13f2f243
commit
0598c9705b
2 changed files with 30 additions and 8 deletions
|
@ -220,25 +220,43 @@ function evaluateServerScript(html) {
|
|||
Object.assign(setupMap, new evalStore())
|
||||
})
|
||||
|
||||
const regex = /{{(.*?)}}/g
|
||||
const regex = /\{\{(.*?)\}\}/g
|
||||
let match
|
||||
|
||||
while ((match = regex.exec(html))) {
|
||||
let [key, value] = match
|
||||
value = value.replace(/\s/g, '')
|
||||
// nested objects
|
||||
let [key, rawValue] = match
|
||||
|
||||
const value = rawValue.replace(/\s/g, '')
|
||||
console.log('>>> value', rawValue)
|
||||
const keys = value.split('.')
|
||||
let finalValue = ''
|
||||
let setupCopy = setupMap
|
||||
|
||||
keys.forEach((i) => {
|
||||
finalValue = setupCopy[i]
|
||||
setupCopy = finalValue
|
||||
// if not in the server script, it could be a js expression
|
||||
if (!(keys[0] in setupMap)) {
|
||||
try {
|
||||
console.log('>>> trying to evaluate', rawValue)
|
||||
finalValue = eval(rawValue)
|
||||
} catch (e) {
|
||||
console.error('ERR! Failed to evaluate expression', e)
|
||||
}
|
||||
}
|
||||
|
||||
// nested objects
|
||||
keys.forEach((key) => {
|
||||
if (key in setupCopy) {
|
||||
finalValue = setupCopy[key]
|
||||
setupCopy = finalValue
|
||||
}
|
||||
})
|
||||
|
||||
html = html.replace(key, finalValue)
|
||||
html = html.replace(key, finalValue ?? '')
|
||||
regex.lastIndex = -1
|
||||
}
|
||||
|
||||
console.log('setupMap', setupMap)
|
||||
console.log('________')
|
||||
|
||||
return html
|
||||
}
|
||||
|
||||
|
|
|
@ -17,6 +17,9 @@
|
|||
function sum(x, y) {
|
||||
return x + y;
|
||||
}
|
||||
|
||||
const hey = 'hey'
|
||||
const world = 'world'
|
||||
</script>
|
||||
</my-head>
|
||||
<body>
|
||||
|
@ -26,6 +29,7 @@
|
|||
<main>
|
||||
<section id="intro">
|
||||
<h1>McFly Demo</h1>
|
||||
<h2>{{ hey }}, {{ world }} {{1+1}} {{hey}} {{3-2}} {{hey}} {{new Date().toString()}}</h2>
|
||||
<warning-block
|
||||
><span>This page is in-progress. See the
|
||||
<a
|
||||
|
|
Loading…
Reference in a new issue