2

If I have an assigns variable, how can I pass that to the Javascript tag? The following would work in Ruby Slim, but does not seem to in Elixir's Slime.

javascript:
  window.currentUser = { username: @username }
steel
  • 11,883
  • 7
  • 72
  • 109

1 Answers1

4

You can inject a value using #{}:

javascript:
  window.currentUser = { username: #{username} }

You'll probably want to JSON encode the variable so that strings are inserted as double quoted escaped JavaScript strings. With Poison, you can do:

javascript:
  window.currentUser = { username: #{Poison.encode!(username)} }

If username is the string foo, the first one will render to:

<script>window.currentUser = { username: foo }</script>

while the second one will render to:

<script>window.currentUser = { username: "foo" }</script>
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • In my case Elixir escaped HTML entities in the JSON string, so I had to additionally [unescape them](https://stackoverflow.com/a/34064434/2750743) – Klesun Feb 11 '20 at 15:08