Closed andymans closed 4 years ago
There are no extra tags but yes this is possible in the expressions via plain JS.
I put together an example here. https://codesandbox.io/s/vigilant-elgamal-nx8nn
const template = () => {
return html`
<div style=${style}>
Sinuous
${() =>
count() >= 3
? html`<b> count ${count}</b>`
: html`<b> cool</b>`
}
</div>
`;
};
Thanks!
Does an ${if...} ${if...else} exist?
I modified the example with if and return statements and works too
const template = () => {
return html`
<div style=${style}>
Sinuous
${() =>{
if (count() >= 3) {
return html`
<b> count ${count}</b>
`
} else {
return html`
<b> cool</b>
`
}
}
}
</div>
`;
It is worth pointing out in all these cases that as count goes to 4, 5, 6, 7, 8 ... You will redoing the work and recreating that template over an over. For a simple case like this that is no problem, but if you have to be careful with conditions and possibly need to hoist the condition if you don't want the parent computed to run over and over.
What does this look like with memoization?
something like this would work https://codesandbox.io/s/thirsty-ptolemy-89qbi
for this example that is definitely overkill I think and a simple hoist like @ryansolid suggested would be better. updated the demo with an example of this
found a slightly cleaner solution that retains the locality: https://codesandbox.io/s/elegant-neumann-mpn0u
there might be an even better one, not sure.
html`${when(
() => count() >= 3,
cond =>
cond
? console.log("render count") ||
html`
<b> count ${count}</b>
`
: console.log("render cool") ||
html`
<b> cool</b>
`
)}`
const when = (condition, view) => {
const memoView = memo((...args) => root(() => view(...args)));
return () => memoView(condition());
};
To any future devs, this might be useful as well: https://github.com/luwes/sinuous/issues/115#issuecomment-647676837
Does an ${if...} ${if...else} exist?