template foo() =
let v = "foo"
let n = nnkInfix.newTree(
newIdentNode("=="),
newIdentNode("v"),
newLit("foo")
)
if n: # here how to embed?
echo "bingo"
You seem to be confused about what a template does and how it relates to a macro. Templates are fairly simple copy-paste expansions (there's a bit more to it than that, but not much). This means that anything which goes into a template has to be valid for where the template is expanded. And unless this is expanded into a macro or a compile-time procedure you can't really create NimNodes in there. Something which would work is this:
import macros
macro mkEqCheck(): untyped =
nnkInfix.newTree(
newIdentNode("=="),
newIdentNode("v"),
newLit("foo")
)
template foo() =
let v {.inject.} = "foo"
if mkEqCheck():
echo "bingo"
foo()
Now there are a couple gotchas here. I've split the check into a macro, here we generate the v == "foo" logic which does the actual comparison. The template now uses {.inject.} on the v symbol to make sure it actually stays as v. This might seem a bit weird, but remember the extras that templates does? Well since it's a copy-paste situation and we want to keep things hygienic the template renames every variable to something else. So your v would actually end up as something like v_38487239 to make sure it doesn't collide with a v outside the template. This means that the newIdentNode("v") would no longer match it. Of course this also means that the v would leak out of the template, and calling this template twice in the same scope would mean that you get a redefinition of v error. You can fix this by passing v explicitly to the macro:
import macros
macro mkEqCheck(x: untyped): untyped =
nnkInfix.newTree(
newIdentNode("=="),
x,
newLit("foo")
)
template foo() =
let v = "foo"
if mkEqCheck(v):
echo "bingo"
foo()
Of course without being able to see what you're actually trying to achieve this might not be helpful. If you share a more realistic code snippet you will get more applicable help.