视图、模板与 LiveView 基础
使用 Phoenix 视图和模板渲染动态内容,并初步了解 Phoenix LiveView 的强大功能。
视图、模板与 LiveView 基础 是 CoddyKit 上的免费 Elixir & Phoenix: Scalable Backend Development 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Elixir & Phoenix: Scalable Backend Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Unlocking Dynamic Content
Web applications aren't static! You need ways to display changing data, like user profiles or product lists. This is where views and templates come in.
They work together to transform raw data from your application into the beautiful HTML that users see in their browsers.
Views: Your Data's Designer
In Phoenix, a View is an Elixir module responsible for preparing data before it's rendered into a template. Think of it as a middleman between your controller and the final HTML.
Views can:
- Format dates or numbers.
- Create dynamic links or URLs.
- Transform complex data structures into simpler ones for display.
Templates: Crafting HTML
Templates are files (often with a .eex extension or using the ~H sigil) that combine standard HTML with embedded Elixir code. Elixir's templating engine, EEx (Embedded Elixir), allows you to inject dynamic content.
<%= expression %>: Evaluates an Elixir expression and outputs its result directly into the HTML.<% expression %>: Evaluates an Elixir expression but does NOT output its result. Useful for control flow like loops or conditionals.
The Rendering Flow in Action
Here's a simplified look at how Phoenix renders a page:
- A Controller action receives an HTTP request.
- The Controller calls
render/3(e.g.,render(conn, "index.html", assigns)), passing data as 'assigns'. - The corresponding View module (e.g.,
PageView) receives these assigns and can apply helper functions. - The Template file (e.g.,
index.html.eex) uses the prepared assigns to generate the final HTML. - This HTML is then sent back to the user's browser.
EEx in Action: Dynamic Greeting
Let's see how EEx processes dynamic data. This Elixir script simulates a template rendering a value passed to it.
defmodule MyTemplateRenderer do
def render_greeting(name) do
template_string = "<h1>Hello, <%= name %>!</h1>"
EEx.eval_string(template_string, [name: name])
end
end
IO.puts MyTemplateRenderer.render_greeting("CoddyKit Learner")Introducing Phoenix LiveView
Imagine building highly interactive web interfaces without writing a single line of JavaScript. That's the magic of Phoenix LiveView!
LiveView allows you to render dynamic, real-time user interfaces entirely on the server, using WebSockets for communication. It brings the power of server-side Elixir directly to your frontend interactions.
LiveView's Core: `mount` & `render`
Every Phoenix LiveView module typically defines at least two key functions:
mount/3: This function is called when the LiveView is first initialized. It's used to set up the initial state (known as 'assigns') of your LiveView.render/1: Takes the current assigns and returns a special HEEx template (using the~Hsigil) to generate the HTML. This function is called automatically whenever the LiveView's state changes.
Adding Interaction: Events
LiveView handles user events (like clicks or form submissions) by sending messages over the WebSocket back to the server. You attach special phx- attributes to your HTML elements to trigger these events.
phx-click="event_name": Triggers a server-side event when the element is clicked.handle_event/3: A callback function in your LiveView module that receives and processes these events, updating the LiveView's state (assigns).
Simple LiveView Counter Concept
Here's a simplified look at a LiveView that implements a basic counter. Notice how handle_event updates the @count assign, which automatically re-renders the template.
defmodule MyAppWeb.CounterLive do
use Phoenix.LiveView, layout: {MyAppWeb.LayoutView, :live}
def mount(_params, _session, socket) do
{:ok, assign(socket, :count, 0)}
end
def render(assigns) do
~H"""
<h1>Count: <%= @count %></h1>
<button phx-click="increment">Increment</button>
"""
end
def handle_event("increment", _value, socket) do
{:noreply, update(socket, :count, &(&1 + 1))}
end
endCheck Your Understanding
In Phoenix, what is the primary purpose of a View module?
Recap: Views, Templates, LiveView
You've learned how Phoenix uses Views to prepare data and Templates (EEx/HEEx) to render dynamic HTML. We also introduced Phoenix LiveView, a powerful tool for building interactive UIs with Elixir, minimizing the need for client-side JavaScript.
Understanding these components is key to building dynamic and engaging web applications with Phoenix. Next, you might explore more advanced LiveView features or dive into data persistence with Ecto!
常见问题解答
「视图、模板与 LiveView 基础」课时是免费的吗?
是的 — 「视图、模板与 LiveView 基础」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Elixir & Phoenix: Scalable Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。
「视图、模板与 LiveView 基础」这节课中我会学到什么?
使用 Phoenix 视图和模板渲染动态内容,并初步了解 Phoenix LiveView 的强大功能。 你通过在浏览器中直接运行的动手代码来练习 Elixir & Phoenix: Scalable Backend Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Elixir & Phoenix: Scalable Backend Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Elixir & Phoenix: Scalable Backend Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「视图、模板与 LiveView 基础」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Elixir & Phoenix: Scalable Backend Development 课中编写并运行代码吗?
能。每节 Elixir & Phoenix: Scalable Backend Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Phoenix 项目设置与结构
- 路由、控制器与 Plugs
- 视图、模板与 LiveView 基础
- 使用 Phoenix Channels 实现实时功能