開發者們,Wubba lubba dub dub!您是否想過透過網頁開發的視角探索《瑞克和莫蒂》的廣闊多元宇宙會是什麼樣子?好吧,拿起你的傳送門槍並做好準備,因為今天我們將這樣做 - 我們將使用 HTMX 和 Express.js 建立一個 Rick 和 Morty 角色資源管理器。本教學的目標是展示使用 HTMX 進行 Web 開發和實作分頁是多麼容易
在這次冒險中,我們將介紹:
設定你的多維工作台
製作 Cosmic 伺服器(Express.js 後端)
在本教程中,我們將使用粉絲製作的《瑞克和莫蒂》API,它允許我們獲取角色列表、他們的位置以及他們出現的劇集。我們也將使用 ejs,一個流行的 javascript 模板引擎,寫出我們的 HTML。 ejs 不是必需的,但以乾淨且可重複使用的方式簡化了 HTML 的編寫。
打開 server.js,讓我們開始編碼:
雷雷
注意我們如何在這裡處理分頁和過濾器。 page 參數決定我們要求的結果頁,而 name 和 status 允許過濾字元。這種靈活性對於我們的 HTMX 分頁實作至關重要。
設計 Multiverse 檢視器(使用 EJS 和 HTMX 的前端)
HTMX 是一個新的 JavaScript 程式庫,可讓您直接在 HTML 中存取 AJAX、CSS 轉換、WebSocket 和伺服器發送事件,而無需編寫 JavaScript(React、Angular、Vue 等)。它就像 Rick 的神經植入物一樣 — 它增強了 HTML 的功能,超出了您最瘋狂的夢想。
在你的views/index.ejs檔案中,加入以下程式碼:
雷雷
實現多維分頁
將此分頁部分新增至您的index.ejs,就在字元表之後:
雷雷
透過利用 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 和 Morty 角色資源管理器的詳細內容。更多資訊請關注PHP中文網其他相關文章!