tmk
LiveView render hook for derived assigns - suggested approaches?
Hey, just getting started with Phoenix + LiveView, coming from Django and React. I’m a bit overwhelmed by the various ways of approaching templating, so apologies in advance if there’s an obvious solution here.
What I’m looking for is the ability to hook into a LiveView render() call, such that I can calculate derived assigns to pass to the template (i.e. so that I can modify assigns). I’d like to do this to keep my LiveView state small and shaped like an entity store, and derive template usage in the render method, as in React.
I understand that function components support this, when leveraging the ~H sigil, but I’m looking to keep my template separate from the LiveView. As an example, the auto generated core components:
def flash(assigns) do
assigns = assign_new(assigns, :id, fn -> "flash-#{assigns.kind}" end)
~H"""
... template here
What I’m looking to do:
@impl true
def render(assigns) do
assigns = derive_view_model(assigns)
actual_render("template.html.heex", assigns)
end
As I understand, LiveView automatically generates a render() function for the template of the same module name. What I’d like to do is understand how to reproduce that method so that I can customize it, or otherwise hook into it.
My current approach is to hook into assign() calls manually - e.g. socket |> delete_entity(:alerts, alert) |> derive_view_model() . However even in my first LiveView page I have forgotten to do this several times, so I’m hoping there’s a better way.
First Post!
krishandley
I have a function called set_state in pretty much every LiveView which basically does this, yes you have to manually call it where needed. But it’s pretty flexible, you could have different ones depending on how expensive they are, and only call them when needed. But there is no automatic way of doing it.
Last Post!
tmk
Thanks for all the suggestions. Coming from a React background, I feel most comfortable with @rhcarvalho ‘s approach to inline templates. In React, I’d map liveview assigns to component state , with the render() method in each supporting derived state.
Popular in Questions
Other popular topics
Latest Phoenix Threads
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









