開發者們,Wubba lubba dub dub!您是否想過透過網頁開發的視角探索《瑞克和莫蒂》的廣闊多元宇宙會是什麼樣子?好吧,拿起你的傳送門槍並做好準備,因為今天我們將這樣做 - 我們將使用 HTMX 和 Express.js 建立一個 Rick 和 Morty 角色資源管理器。本教學的目標是展示使用 HTMX 進行 Web 開發和實作分頁是多麼容易
在這次冒險中,我們將介紹:
無論您是新手程式設計師還是希望提升水平的經驗豐富的開發人員,本指南都將幫助您創建一個令人印象深刻的 Web 應用程式。
在我們開始在維度之間跳躍之前,我們需要設定我們的跨維度工作台。可以將其視為整理 Rick 的車庫,但使用更少的死亡射線和更多的 JavaScript。
mkdir rick-and-morty-explorer cd rick-and-morty-explorer npm init -y npm install express axios ejs
rick-and-morty-explorer/ ├── node_modules/ ├── public/ │ └── styles.css ├── views/ │ └── index.ejs ├── package.json └── server.js
現在我們的工作台已經設定完畢,讓我們繼續製作我們的宇宙伺服器。
現在,讓我們建立 Express.js 伺服器。這就像建造我們傳送門槍的引擎 - 它為我們的跨維度旅行提供動力。
在本教程中,我們將使用粉絲製作的 Rick 和 Morty API,它允許我們獲取角色列表、他們的位置以及他們出現的劇集。我們也將使用 ejs,一個流行的 javascript 模板引擎,寫出我們的 HTML。 ejs 不是必需的,但以乾淨且可重複使用的方式簡化了 HTML 的編寫。
開啟server.js,讓我們開始編碼:
const express = require('express'); const axios = require('axios'); const app = express(); app.use(express.static('public')); app.set('view engine', 'ejs'); const BASE_URL = 'https://rickandmortyapi.com/api/character'; app.get('/', async (req, res) => { const { page = 1, name, status } = req.query; let url = `${BASE_URL}?page=${page}`; if (name) url += `&name=${name}`; if (status) url += `&status=${status}`; try { const response = await axios.get(url); res.render('index', { data: response.data, query: req.query }); } catch (error) { console.error('Error fetching data:', error.message); res.status(500).render('error', { message: 'Error fetching data' }); } }); app.listen(3000, () => console.log('Server running on port 3000'));
這個伺服器設定就像 Rick 的車庫 - 這是所有魔法發生的地方。我們使用 Express 來建立伺服器並處理路由。主路由 (/) 是我們根據查詢參數從 Rick 和 Morty API 取得角色資料的地方。
請注意我們如何在這裡處理分頁和過濾器。 page 參數決定我們要求的結果頁,而 name 和 status 允許過濾字元。這種靈活性對於我們的 HTMX 分頁實作至關重要。
我們的宇宙伺服器就位後,我們需要一種查看多元宇宙的方法。輸入 EJS 和 HTMX——我們的多維觀看螢幕和高效的小工具設計。
HTMX 是一個新的 JavaScript 程式庫,可讓您直接在 HTML 中存取 AJAX、CSS 轉換、WebSocket 和伺服器發送事件,而無需編寫 JavaScript(React、Angular、Vue 等)。它就像 Rick 的神經植入物一樣 — 它增強了 HTML 的功能,超出了您最瘋狂的夢想。
在你的views/index.ejs 檔案中,加入以下程式碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Rick and Morty Explorer</title> <script src="https://unpkg.com/htmx.org@1.9.10"></script> <link rel="stylesheet" href="/styles.css"> </head> <body> <h1>Rick and Morty Character Explorer</h1> <!-- Filter section will go here --> <div id="character-table"> <% if (data.results && data.results.length > 0) { %> <table> <thead> <tr> <th>Image</th> <th>Name</th> <th>Status</th> <th>Species</th> <th>Origin</th> <th>Actions</th> </tr> </thead> <tbody> <% data.results.forEach(character => { %> <tr> <td><img src="<%= character.image %>" alt="<%= character.name %>" width="50"></td> <td><%= character.name %></td> <td><%= character.status %></td> <td><%= character.species %></td> <td><%= character.origin.name %></td> <td><a href="/character/<%= character.id %>" hx-get="/character/<%= character.id %>" hx-target="body" hx-push-url="true">View More</a></td> </tr> <% }); %> </tbody> </table> <!-- Pagination section will go here --> </body> </html>
上面的程式碼為我們的網站設定了一個基本表格,我們將在下一節中使用 HTMX 新增分頁和篩選。
現在,讓我們實現分頁,這是我們應用程式的跨維度旅行機制。這就是 HTMX 真正閃光的地方,它使我們能夠實現流暢的伺服器端分頁,而無需任何自訂 JavaScript。
將此分頁部分新增至您的index.ejs,就在字元表之後:
<div class="pagination"> <% const currentPage = parseInt(query.page) || 1; %> <% if (data.info.prev) { %> <a href="/?page=<%= currentPage - 1 %><%= query.name ? `&name=${query.name}` : '' %><%= query.status ? `&status=${query.status}` : '' %>" hx-get="/?page=<%= currentPage - 1 %><%= query.name ? `&name=${query.name}` : '' %><%= query.status ? `&status=${query.status}` : '' %>" hx-target="body" hx-push-url="true">Previous</a> <% } %> <span>Page <%= currentPage %> of <%= data.info.pages %></span> <% if (data.info.next) { %> <a href="/?page=<%= currentPage + 1 %><%= query.name ? `&name=${query.name}` : '' %><%= query.status ? `&status=${query.status}` : '' %>" hx-get="/?page=<%= currentPage + 1 %><%= query.name ? `&name=${query.name}` : '' %><%= query.status ? `&status=${query.status}` : '' %>" hx-target="body" hx-push-url="true">Next</a> <% } %> </div>
這個分頁部分是我們 HTMX 實作皇冠上的寶石。讓我們來分解一下:
這個 HTMX 分頁的美妙之處在於它的簡單性和效率。我們能夠實現流暢的伺服器端分頁,而無需編寫一行自訂 JavaScript。它就像瑞克的傳送槍一樣無縫 - 點擊鏈接,您會立即傳送到下一頁的角色。
透過利用 HTMX,我們創建了一個分頁系統,該系統不僅易於實現,而且還提供流暢、類似應用程式的使用者體驗。它速度很快,可以在頁面載入時保持狀態,並且使用最少的 Javascript。
Let's take our interdimensional exploration to the next level by adding filters to our character explorer. Think of this as tuning into different channels on interdimensional cable – you want to find the right show (or character) amidst the multiverse chaos.
Add this filter section to your index.ejs file, right above the character table:
<form id="filter-form" hx-get="/" hx-target="body" hx-push-url="true"> <input type="text" name="name" placeholder="Name" value="<%= query.name || '' %>"> <select name="status"> <option value="">All Statuses</option> <option value="alive" <%= query.status === 'alive' ? 'selected' : '' %>>Alive</option> <option value="dead" <%= query.status === 'dead' ? 'selected' : '' %>>Dead</option> <option value="unknown" <%= query.status === 'unknown' ? 'selected' : '' %>>Unknown</option> </select> <button type="submit">Filter</button> </form>
These filters allow users to narrow down their search, just like Rick tuning his interdimensional cable to find the perfect show. Enhanced with the power HTMX, our filter implementation is powerful and intuitive, providing real-time updates without needing custom JavaScript. Our app with both filters and pagination should look like this:
Now that our Rick and Morty Character Explorer looks slick and functional, it's time to add another exciting feature: individual character profiles. Imagine diving into a detailed dossier on Morty or Rick, complete with all their vital stats and episode appearances. Let's add a "View More" button to our character table to take users to a detailed character profile page.
Let's add a new route to our server.js file:
// Route to display character details app.get('/character/:id', async (req, res) => { const { id } = req.params; try { const response = await axios.get(`${BASE_URL}/${id}`); res.render('character', { character: response.data }); } catch (error) { console.error('Error fetching character details:', error.message); res.status(500).render('error', { message: 'Error fetching character details' }); } });
Let's also add a new file views/character.ejs the necessary HTML for our character detail page:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><%= character.name %> - Details</title> <link rel="stylesheet" href="/styles.css"> </head> <body> <h1><%= character.name %> - Details</h1> <div class="character-details"> <img src="<%= character.image %>" alt="<%= character.name %>"> <ul> <li><strong>Status:</strong> <%= character.status %></li> <li><strong>Species:</strong> <%= character.species %></li> <li><strong>Gender:</strong> <%= character.gender %></li> <li><strong>Origin:</strong> <%= character.origin.name %></li> <li><strong>Location:</strong> <%= character.location.name %></li> </ul> <h2>Episodes</h2> <ul> <% character.episode.forEach(episode => { %> <li><a href="<%= episode %>" target="_blank">Episode <%= episode.split('/').pop() %></a></li> <% }); %> </ul> </div> <a href="/" hx-get="/" hx-target="body" hx-push-url="true" class="back-link">Back to Character List</a> </body> </html>
The code above defines a new route on our web server /character/:id. This new route is resolved when the user clicks on the view more option in the characters table. It fetches details for the specific character and returns a neatly rendered HTML page with all the character details. This page will look like this:
Now that we've built our interdimensional travel device, it's time to see it in action. Here's a complete overview of our code, bringing together everything we've covered so far and also defining custom CSS styles to make the application look better.
Congratulations—you've just built an interdimensional character explorer! In this adventure, we've covered a lot of ground, from setting up our Express.js server and designing a dynamic frontend with EJS and HTMX to implementing smooth pagination and filters.
This project is a testament to the power of HTMX. It shows how we can create dynamic, server-side rendered applications with minimal JavaScript. It's fast, efficient, and user-friendly—just like Rick's portal gun.
But don't stop here! There's a whole multiverse of possibilities waiting for you. Experiment with new features, add more filters or integrate additional APIs. The only limit is your imagination.
Before you go, here are some additional resources to help you on your journey:
And for those who made it to the end, here are a few hidden Rick and Morty references:
Happy coding, and may your interdimensional travels be filled with endless possibilities!
以上是使用 HTMX 和 Express.js 建立 Rick and Morty 角色資源管理器的詳細內容。更多資訊請關注PHP中文網其他相關文章!