funboy
1
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"]
funboy
2
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, ", ")
funboy
4
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? 
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
funboy
6
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 