I defined a helper function in the view:
def usernames(id) do
post = Repo.get(Post, id) |> Repo.preload(comments: :user)
usernames = for comment <- post.comments do
comment.user.username
end
end
Then in the javascript file I do:
$('#comment').doThis({
data: "<%= escape_javascript( MyApp.ApplicationHelpers.usernames(@post.id) ) %>"
});
The above does not work. Of course I need to be able to pass in the @post.id, but even by hardcoding a post id like MyApp.ApplicationHelpers.usernames(5), doesn't work.
Basically I am trying to do the Rails equivalent of:
@usernames = User.pluck(:username)
Then in the js.erb would have been:
data = <% @usernames %>
$('#comment').doThis({'data': data});
If someone can help out in how to achieve this...
Update: (to provide additional info)
I put the javascript code in posts.js as following this stackoverflow answer. Other javascript code in that file executes as needed.
windowobject, data attributes or separate JSON endpoint would be feasible. If you're concerned with the size of the data attribute - in HTML 5 there is no size limit on attributes so you should be fine. Just wanted to let you know that embedding Elixir code in static assets is not really an option with Phoenix and which solutions exist to handle such situations.