How to use a Phoenix controller variable in JavaScript?

孤街浪徒 提交于 2019-12-13 19:08:19

问题


How do I use a variable from Phoenix controller in my JavaScript?

I'm using React for front-end.

I can't 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

回答1:


You could try rendering the value in view to build HTML attribute and then obtain this with your JavaScript, which is rather common prctice.

Something like this could do:

my_view.eex

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

script.js

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

You can find more about data here

Hope that helps!




回答2:


You can use PhoenixGon it bring all phoenix variables to window scope and you can use all this variables, and it also generate js methods for getting this vars:

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

and use it from browser console or in javascript module:

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

It also helps keep js vars and html.eex vars in different parts and keeps it clear.



来源:https://stackoverflow.com/questions/36838456/how-to-use-a-phoenix-controller-variable-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!