I see 3 ways of doing this.
<%= %>
inside <script>
in *.html.eex
#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.
No JavaScript. You don't need any JavaScript to build web applications with LiveView.
There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.
(2) is not a good idea if you don't want real time updates. (3) may be too unnecessarily complicated if you don't want to load the data using AJAX. You should use (1) if you just need some data to be accessible from JS and don't want to change it without a whole page reload.
Since valid JSON is also valid JS, you can just use Poison.encode!()
. If your data is in @posts
, you can do this in *.html.eex
:
<script>
var POSTS = <%= Poison.encode!(@posts) %>;
</script>
and then load other JS after this and access the posts using the global POSTS
variable. (You might want to namespace it into something like App.posts = ...
:
<script>
var App = window.App || {};
App.posts = <%= Poison.encode!(@posts) %>;
</script>
Make sure @posts
only contains data that can be converted to JSON (no tuples) and only has the fields that the user is allowed to see.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With