Best practices for transferring data from Phoenix to Javascript

I see 3 ways to do this.

  • Use <%= %>inside <script>in*.html.eex
  • Use channels to transfer data in Javascript
  • Create json api

# 1 seems the easiest, but I couldn't find or think of a good way to do it yet.

Note. Real-time update is not my requirement.

+4
source share
4 answers

(2) , . (3) , AJAX. (1), , JS, .

JSON JS, Poison.encode!(). @posts, *.html.eex:

<script>
  var POSTS = <%= Poison.encode!(@posts) %>;
</script>

JS , POSTS. (, , App.posts = ...:

<script>
  var App = window.App || {};
  App.posts = <%= Poison.encode!(@posts) %>;
</script>

, @posts , JSON ( ), , .

+2

<script></script> , :

<!-- Layout -->
<div id="config"
  data-environment="..."
></div>

, config.js .

javascript, - :

<div id="app"
  data-users="..."
  data-zombies="..."
  ...
></div>

( ), :

<%= App.Helpers.make_html(:app, [users: @users, zombies: @zombies]) %>

javascript data- options :

class ZombieController extends Controller

  setup: ->

    console.log(@options) # I have all the data there.

    # I can do 
    zombies = @options.zombies

, , . .

, :)

+2

.

HTML- javascript. html script

/ angular/front end, API / .

, -, javascript, API/.

+1

You can also use hex PhoenixGon , it uses the first way to pass Phoenix variables to Javascript. It takes all the variables from the controller and Mix.env and generates a tag <script>with visualized JSONand access methods for this data. Other answers are here . Like it:

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

And in js code:

window.Gon.getAsset('users') #=> [user list]
windoe.Gon.isDev() # => true

And you do not need to create @vars and keep it clear.

And for zommbies.coffee:

class ZombieController extends Controller

  setup: ->

    zombies = window.Gon.getAsset('zombies')
+1
source

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


All Articles