How to use Phoenix controller variable in JavaScript?

How to use variable from phoenix controller in my javascript?

I use React for front-end.

I can not use <%= ... %>in JavaScript.

defmodule Familytree.PageController do
  use Familytree.Web, :controller

  alias Familytree.Users
  alias Familytree.Tags
  alias Familytree.UserTag

  plug Familytree.Plugs.Auth
  plug :scrub_params, "users" when action in [:create, :update]
  plug :scrub_params, "tags" when action in [:add_tag,:delete_tag]

  def index(conn, _params) do
    users = Repo.all(Users)
    tags = Repo.all(Tags)
    render(conn, "index.html", users: users, tags: tags, current_user: get_session(conn, :current_user))
  end
end
0
source share
2 answers

You can try to show the value to create the HTML attribute, and then get it using your JavaScript, which is a fairly common prctice.

Something like this might do:

my_view.eex

<div data-name="<%= @some_name_from_controller %>" id="component">
</div>

script.js

var name = $("#component").data("name");

Read more about data here

Hope this helps!

0
source

PhoenixGon, phoenix , , js- :

def index(conn, _params) do
  put_gon(conn, [users: Repo.all(Users), tags: Repo.all(Tags)])
  render(conn, "index.html", current_user: get_session(conn, :current_user))
end

javascript:

window.Gon.getAsset('users')
// => [user, user1 ...]

js vars html.eex vars .

0

Source: https://habr.com/ru/post/1651871/


All Articles