HEex alpineJS interpolation

Hi there, as the title indicates, I’m trying to understand how to perform string interpolation correctly in AlpineJS within a .heex template.

Here’s the code that I’ve seen around and that fails:

    x-init="() => {
      setTimeout(() => open = true, 100);
      $watch('open', isOpen => $dispatch('modal-change', { open: isOpen, id: '#<%= @id %>' }))
    }"

If I proceed to fix it as mentioned in the error that’s displayed, I arrive at this code:

    x-init="() => {
      setTimeout(() => open = true, 100);
      $watch('open', isOpen => $dispatch('modal-change', { open: isOpen, id: {@id} }))
    }"

It also doesn’t work since the {@id} is being interpreted as text. I have tried but failed to find a way to maybe break into 3 different strings and concatenate it with + or some sort of interpolation.

Any feedback is appreciated, thanks!

It seems like that at least for now one needs to do the following:

x-init={"""
() => {
  setTimeout(() => open = true, 100);
  $watch('open', isOpen => $dispatch('modal-change', { open: isOpen, id: '##{@id}' }))
}\
"""}

Maybe later it’d be possible to interpolate with ~E or iolists.

2 Likes

That’s a solid way to advance for the time being, appreciated!