Using script tags in HEEX does not work?

I’ve been converting my EEX and LEEX to HEEX and so far it’s been working fine. But I ran into one problem that I couldn’t figure out.

If you have some javascript with string interpolation (e.g. to set a token), it throws errors about it.

Is HEEX intended to support <script> tags?

I was trying to do something like this:

<script>
  fun("<%= @token %>");
</script>

I also tried this:

<script>
  fun({@token});
</script>

The error is:

UndefinedFunctionError{arity: 1, function: :init, message: nil, module: AllegroWeb.Router, reason: nil}, [{AllegroWeb.Router, :init, [[]], []}, {AllegroWeb.Endpoint, :plug_builder_call, 2, [file: 'lib/allegro_web/endpoint.ex', line: 1]}, {AllegroWeb.Endpoint, :"call (overridable 3)", 2, [file: 'lib/plug/debugger.ex', line: 132]},

I know it looks weird that it can’t find Router.init, but I can confirm that is truly the error that happens, and if I change it back to leex it works fine again.

Thanks!

<script>
  <%= render_script(@token) %>
</script>

defp render_script(token) do
  ~E"fun(<%= token %>)"
end

Might be not ideal, but that seems to work for me.

is fun an Elixir function? If so, that should be inside the <%= %>, not outside.

I have script tags which are calling Elixir functions in several of my heex templates - no issues so far.

Ah, I didn’t make that clear. It’s a JavaScript function.

Can you do something like this?

<script>
  const myToken = "<%= @token %>";
  fun(myToken);
</script>

I would use hooks for this and not this sort of thing.

1 Like