[英]Load environment variable in template file in Phoenix Framework
[英]How to use variable in phoenix framework in a handle_event function?
我想有两种不同形式的两个输入字段(见下文)。 第一个提交用户名并将其保存在变量 client_name 中。 这似乎工作正常。
当第二个提交时,我想抓住 client_name 变量并在我创建的字符串中使用它。 但我不知道怎么办。
defmodule ChatWeb.ChatLive do
use ChatWeb, :live_view
@topic "message_received"
def mount(params, session, socket) do
ChatWeb.Endpoint.subscribe(@topic)
{:ok, assign(socket, :text_value, "") |>assign(:client_name, "")}
end
def render(assigns) do
~H"""
<h1>Chat</h1>
<form phx-submit="submit_name">
<label>Your name: <%= @client_name %><input id="client" type="text" name="client" /></label>
<input type="submit" />
</form>
<form phx-submit="submit">
<label>Your Text:<input id="msg" type="text" name="input_value" /></label>
<input type="submit" />
</form>
<div id="chat">
Chat history: <%= @text_value %>
</div>
"""
end
def handle_event("submit_name", %{"client" => client}, socket) do
{:noreply, assign(socket, :client_name, client)}
end
def handle_event("submit", %{"input_value" => msg}, socket) do
ChatWeb.Endpoint.broadcast_from(self(), @topic, "message_received_received", "| Message by #{client_name}: '" <> msg <> "' ")
{:noreply, assign(socket, :text_value, "| Message by #{client_name}: '" <> msg <> "' " <> socket.assigns.text_value)}
end
def handle_info(%{topic: @topic, payload: new_message}, socket ) do
{:noreply, assign(socket, :text_value, new_message <> socket.assigns.text_value)}
end
结尾
问题出在#{client_name} 什么是正确的表示法?
我的错误是:undefined function client_name/0
您对client_name
的调用应更改为socket.assigns.client_name
因为这是您将值放入handle_event("submit_name", ...)
的位置。
或者,您可以在函数子句中绑定client_name
赋值:
def handle_event("submit", %{"input_value" => msg}, %{assigns: %{client_name: client_name}} = socket) do
在这种情况下,您不需要在函数体中修复client_name
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.