Get list of strings in html.eex from assings

Hi All,
How could I get list from assing in html.eex?
I’ve tried that

//elixir
    names = ["Tom","Kate"]
    conn = assign(conn, :names, names)

//html
 var all_users = "<%= assigns.names %>";  // this is TomKate

but under all_users is "TomKate" string instead of list of strings ["Tom","Kate"]

Ok, I’ve done it by that line of code

    var all_users = [<%= @names |> Enum.map(&(raw("\"#{&1}\"\,")))  %> ]

which returns

  var all_users = ["Tom","Kate", ]

Enum.join should also work…

Enum.join(@names, ", ")
Enum.join(@names, ", ")

produce

 var all_users =  [Tom, Kate]

and error

Uncaught ReferenceError: Tom  is not defined

We have to add quotes around too.
Do you know maybe how to do it simpler? :smiley:

Oh… You mean You want it in javascript.

I usually pass value to js as a json serialized data attribute.

Something like this…

<div id="all-users" data-users="<%= Jason.encode!(@names) %>">

# in js

const element = document.getElementById("all-users");
const { users } = element.dataset
allUsers = JSON.parse(users)
1 Like

Great, thanks!
One more question.
It is possible to do it without div tag?

You need a tag, any tag where You can put attribute :slight_smile:

Ok, thanks :slight_smile: