簡體   English   中英

如何使變量在多個模板中全局可訪問

[英]How to make a variable globally accessible across multiple templates

在我的 phoenix 應用程序中,我正在嘗試加載一堆數據並使它們可以訪問我的根模板(跨所有頁面)。 據我所知,這是通過分配完成的,但我不知道在哪里加載它。

我想像

use App.LiveView
use App.News

assign(socket, news: News.all)

應該可以工作,但我不知道把這段代碼放在哪里,所以套接字是可用的。 來自 Express.js,我想做類似的事情:

router.use((req, res, next) => {
  // Load news into global variable
  // ...
  next()
})

感謝您的幫助。

Express 的router.use的非 LiveView Phoenix 等效項是Router.plug/2 您可以在管道中添加一個插件。

一個插頭既可以定義為一個模塊,也可以定義為一個簡單的 function。

這是一個最小的例子:

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    # ...
    plug :my_plug  # <= add your plug
  end

  def my_plug(conn, _opts) do
    Plug.Conn.assign(conn, :news, News.all())
  end

但這不適用於 LiveView,它無法訪問插頭分配。 從 LiveView 0.17 開始,您可以使用掛載掛鈎來實現此目的。 您需要將on_mount/1添加到AppWeb.live_view/0

def live_view do
  quote do
    use Phoenix.LiveView,
      layout: {AppWeb.LayoutView, "live.html"}

    on_mount AppWeb.NewsLiveFetcher  # <= add this
    unquote(view_helpers())
  end
end

並實現AppWeb.NewsLiveFetcher類似:

defmodule AppWeb.NewsLiveFetcher do
  import Phoenix.LiveView

  def on_mount(:default, _params, _session, socket) do
    socket = assign_new(socket, :news, &News.all/0)
    {:cont, socket}
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM