Rick and Morty Character Explorer

<% if (data.results && data.results.length > 0) { %> <% data.results.forEach(character => { %> <% }); %>
Image Name Status Species Origin Actions
\\\"使用\\\" alt=\\\"<%= character.name %>\\\" width=\\\"50\\\"> <%= character.name %> <%= character.status %> <%= character.species %> <%= character.origin.name %> \\\" hx-target=\\\"body\\\" hx-push-url=\\\"true\\\">View More

The above code sets up a basic table for our website, we will add pagination and filtering using HTMX in the following section.

Implementing Interdimensional Pagination

Now, let\\'s implement pagination, our app\\'s interdimensional travel mechanism. This is where HTMX really shines, allowing us to implement smooth, server-side pagination without any custom JavaScript.

Add this pagination section to your index.ejs, just after the character table:

This pagination section is the crown jewel of our HTMX implementation. Let\\'s break it down:

The beauty of this HTMX pagination is its simplicity and efficiency. We\\'re able to implement smooth, server-side pagination without writing a single line of custom JavaScript. It\\'s as seamless as Rick\\'s portal gun – click a link, and you\\'re instantly transported to the next page of characters.

By leveraging HTMX, we\\'ve created a pagination system that\\'s not only easy to implement but also provides a smooth, app-like user experience. It\\'s fast, maintains state across page loads, and uses minimal Javascript.

Crafting the Multiverse Filter

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:

\\\">

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:

\\\"Rick

Creating Character Profiles: Adding the Details Screen

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 detailsapp.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:

            <%= character.name %> - Details        

<%= character.name %> - Details

\\\"使用\\\" alt=\\\"<%= character.name %>\\\">
  • Status: <%= character.status %>
  • Species: <%= character.species %>
  • Gender: <%= character.gender %>
  • Origin: <%= character.origin.name %>
  • Location: <%= character.location.name %>

Episodes

Back to Character List

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:
\\\"Character

Putting It All Together: Your Interdimensional Character Explorer

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.

Conclusion: Your Portal to Advanced Web Development

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.

\\\"Post-Credits Scene\\\": Additional Resources and Easter Eggs

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!

","image":"http://www.luping.net/uploads/424/1f1bb5f5a631e38294a42ac9fa5400ee.png","datePublished":"2024-08-09T09:00:03+08:00","dateModified":"2024-08-09T09:00:04+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 HTMX 和 Express.js 建立 Rick and Morty 角色資源管理器

使用 HTMX 和 Express.js 建立 Rick and Morty 角色資源管理器

發佈於2024-08-09
瀏覽:198

Wubba lubba dub dub, developers! Have you ever wondered what it would be like to explore the vast multiverse of Rick and Morty through the lens of web development? Well, grab your portal guns and get ready, because today we'll do just that – we're going to build a Rick and Morty Character Explorer using HTMX and Express.js. The goal of this tutorial is to show how easy it is to do web dev and implement pagination using HTMX

In this adventure, we'll cover:

  • Setting up an Express.js server (our interdimensional travel device)
  • Creating a dynamic frontend with EJS and HTMX (our portal viewer)
  • Implementing smooth, server-side pagination with HTMX (our method of jumping between dimensions)

Whether you're a rookie programmer or a seasoned dev looking to level up, this guide will help you create a web app that's burp seriously impressive.

Setting Up Your Interdimensional Workbench

Before we can start hopping between dimensions, we need to set up our interdimensional workbench. Think of this as organizing Rick's garage but with fewer death rays and more JavaScript.

  1. First, ensure you have Node.js installed. If not, you can download it from nodejs.org.
  2. Next, we'll set up our project directory and install the necessary packages. Open your terminal and run the following commands:
mkdir rick-and-morty-explorer
cd rick-and-morty-explorer
npm init -y
npm install express axios ejs
  1. Project Structure: Organizing our project is akin to arranging Rick's gadgets. Here's a basic structure:
rick-and-morty-explorer/
├── node_modules/
├── public/
│   └── styles.css
├── views/
│   └── index.ejs
├── package.json
└── server.js

Now that our workbench is set up, let's move on to crafting our cosmic server.

Crafting the Cosmic Server (Express.js Backend)

Now, let's create our Express.js server. This is like building the engine of our portal gun - it's what powers our interdimensional travels.

In this tutorial, we shall be using a fan-made Rick and Morty API that allows us to fetch a list of characters, their locations, and the episodes they appeared in. We will also be using ejs, a popular javascript templating engine, to write out our HTML. ejs is not required but simplifies writing our HTML in a clean and reusable way.

Open up server.js, and let's get coding:

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'));

This server setup is like Rick's garage – it's where all the magic happens. We're using Express to create our server and handle routing. The main route (/) is where we'll fetch character data from the Rick and Morty API based on the query parameters.

Notice how we're handling pagination and filters here. The page parameter determines which page of results we're requesting, while name and status allow for filtering characters. This flexibility is crucial for our HTMX pagination implementation.

Designing the Multiverse Viewer (Frontend with EJS and HTMX)

With our cosmic server in place, we need a way to view the multiverse. Enter EJS and HTMX—our multidimensional viewing screen and efficient gadget designs.

HTMX is a new JavaScript library that allows you to access AJAX, CSS Transitions, WebSockets, and Server-Sent Events directly in HTML without writing JavaScript (React, Angular, Vue, etc.). It's like Rick's neural implant—it enhances HTML's capabilities beyond your wildest dreams.

In your views/index.ejs file, add the following code:



    
    
    Rick and Morty Explorer
    
    


    

Rick and Morty Character Explorer

0) { %> { %>
Image Name Status Species Origin Actions
" alt="" width="50"> " hx-target="body" hx-push-url="true">View More

The above code sets up a basic table for our website, we will add pagination and filtering using HTMX in the following section.

Implementing Interdimensional Pagination

Now, let's implement pagination, our app's interdimensional travel mechanism. This is where HTMX really shines, allowing us to implement smooth, server-side pagination without any custom JavaScript.

Add this pagination section to your index.ejs, just after the character table:


This pagination section is the crown jewel of our HTMX implementation. Let's break it down:

  • We calculate the current page and check if there are previous or next pages.
  • The hx-get attribute on each link tells HTMX to make a GET request to our server with the appropriate page number and any active filters.
  • hx-target="body" ensures that the entire page content is updated when navigating.
  • hx-push-url="true" updates the URL, allowing users to share or bookmark specific pages.

The beauty of this HTMX pagination is its simplicity and efficiency. We're able to implement smooth, server-side pagination without writing a single line of custom JavaScript. It's as seamless as Rick's portal gun – click a link, and you're instantly transported to the next page of characters.

By leveraging HTMX, we've created a pagination system that's not only easy to implement but also provides a smooth, app-like user experience. It's fast, maintains state across page loads, and uses minimal Javascript.

Crafting the Multiverse Filter

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:

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:

Rick and Morty Explorer Web App

Creating Character Profiles: Adding the Details Screen

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:



    
    
     - Details
    


    

- Details

" alt="">
  • Status:
  • Species:
  • Gender:
  • Origin:
  • Location:

Episodes

Back to Character List

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:
Character Detail Page

Putting It All Together: Your Interdimensional Character Explorer

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.

Conclusion: Your Portal to Advanced Web Development

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.

"Post-Credits Scene": Additional Resources and Easter Eggs

Before you go, here are some additional resources to help you on your journey:

  • HTMX Documentation
  • Express.js Documentation
  • Rick and Morty API

And for those who made it to the end, here are a few hidden Rick and Morty references:

  • Remember, "Wubba Lubba Dub Dub!" means you're in great pain, but also having a great time coding.
  • Lastly, always be like Rick – curious, inventive, and never afraid to break the rules (of JavaScript).

Happy coding, and may your interdimensional travels be filled with endless possibilities!

版本聲明 本文轉載於:https://dev.to/mikeyny_zw/building-a-rick-and-morty-character-explorer-with-htmx-and-expressjs-12n3?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何高效地在一個事務中插入數據到多個MySQL表?
    如何高效地在一個事務中插入數據到多個MySQL表?
    mySQL插入到多個表中,該數據可能會產生意外的結果。雖然似乎有多個查詢可以解決問題,但將從用戶表的自動信息ID與配置文件表的手動用戶ID相關聯提出了挑戰。 使用Transactions和last_insert_id() 插入用戶(用戶名,密碼)值('test','tes...
    程式設計 發佈於2025-05-23
  • 如何在鼠標單擊時編程選擇DIV中的所有文本?
    如何在鼠標單擊時編程選擇DIV中的所有文本?
    在鼠標上選擇div文本單擊帶有文本內容,用戶如何使用單個鼠標單擊單擊div中的整個文本?這允許用戶輕鬆拖放所選的文本或直接複製它。 在單個鼠標上單擊的div元素中選擇文本,您可以使用以下Javascript函數: function selecttext(canduterid){ if(d...
    程式設計 發佈於2025-05-23
  • 在Java中使用for-to-loop和迭代器進行收集遍歷之間是否存在性能差異?
    在Java中使用for-to-loop和迭代器進行收集遍歷之間是否存在性能差異?
    For Each Loop vs. Iterator: Efficiency in Collection TraversalIntroductionWhen traversing a collection in Java, the choice arises between using a for-...
    程式設計 發佈於2025-05-23
  • 如何將多種用戶類型(學生,老師和管理員)重定向到Firebase應用中的各自活動?
    如何將多種用戶類型(學生,老師和管理員)重定向到Firebase應用中的各自活動?
    Red: How to Redirect Multiple User Types to Respective ActivitiesUnderstanding the ProblemIn a Firebase-based voting app with three distinct user type...
    程式設計 發佈於2025-05-23
  • 如何使用替換指令在GO MOD中解析模塊路徑差異?
    如何使用替換指令在GO MOD中解析模塊路徑差異?
    在使用GO MOD時,在GO MOD 中克服模塊路徑差異時,可能會遇到衝突,其中3個Party Package將另一個PAXPANCE帶有導入式套件之間的另一個軟件包,並在導入式套件之間導入另一個軟件包。如迴聲消息所證明的那樣: go.etcd.io/bbolt [&&&&&&&&&&&&&&&&...
    程式設計 發佈於2025-05-23
  • Async Void vs. Async Task在ASP.NET中:為什麼Async Void方法有時會拋出異常?
    Async Void vs. Async Task在ASP.NET中:為什麼Async Void方法有時會拋出異常?
    在ASP.NET async void void async void void void void void的設計無需返回asynchroncon而無需返回任務對象。他們在執行過程中增加未償還操作的計數,並在完成後減少。在某些情況下,這種行為可能是有益的,例如未期望或明確預期操作結果的火災和...
    程式設計 發佈於2025-05-23
  • 表單刷新後如何防止重複提交?
    表單刷新後如何防止重複提交?
    在Web開發中預防重複提交 在表格提交後刷新頁面時,遇到重複提交的問題是常見的。要解決這個問題,請考慮以下方法: 想像一下具有這樣的代碼段,看起來像這樣的代碼段:)){ //數據庫操作... 迴聲“操作完成”; 死(); } ? > ...
    程式設計 發佈於2025-05-23
  • 如何干淨地刪除匿名JavaScript事件處理程序?
    如何干淨地刪除匿名JavaScript事件處理程序?
    刪除匿名事件偵聽器將匿名事件偵聽器添加到元素中會提供靈活性和簡單性,但是當要刪除它們時,可以構成挑戰,而無需替換元素本身就可以替換一個問題。 element? element.addeventlistener(event,function(){/在這里工作/},false); 要解決此問題,請考...
    程式設計 發佈於2025-05-23
  • Python不會對超範圍子串切片報錯的原因
    Python不會對超範圍子串切片報錯的原因
    在python中用索引切片範圍:二重性和空序列索引單個元素不同,該元素會引起錯誤,切片在序列的邊界之外沒有。 這種行為源於索引和切片之間的基本差異。索引一個序列,例如“示例” [3],返回一個項目。但是,切片序列(例如“示例” [3:4])返回項目的子序列。 索引不存在的元素時,例如“示例” [9...
    程式設計 發佈於2025-05-23
  • C++中如何將獨占指針作為函數或構造函數參數傳遞?
    C++中如何將獨占指針作為函數或構造函數參數傳遞?
    在構造函數和函數中將唯一的指數管理為參數 unique pointers( unique_ptr [2啟示。通過值: base(std :: simelor_ptr n) :next(std :: move(n)){} 此方法將唯一指針的所有權轉移到函數/對象。指針的內容被移至功能中,在操作...
    程式設計 發佈於2025-05-23
  • Python中嵌套函數與閉包的區別是什麼
    Python中嵌套函數與閉包的區別是什麼
    嵌套函數與python 在python中的嵌套函數不被考慮閉合,因為它們不符合以下要求:不訪問局部範圍scliables to incling scliables在封裝範圍外執行範圍的局部範圍。 make_printer(msg): DEF打印機(): 打印(味精) ...
    程式設計 發佈於2025-05-23
  • 為什麼不使用CSS`content'屬性顯示圖像?
    為什麼不使用CSS`content'屬性顯示圖像?
    在Firefox extemers屬性為某些圖像很大,&& && && &&華倍華倍[華氏華倍華氏度]很少見,卻是某些瀏覽屬性很少,尤其是特定於Firefox的某些瀏覽器未能在使用內容屬性引用時未能顯示圖像的情況。這可以在提供的CSS類中看到:。 googlepic { 內容:url(&...
    程式設計 發佈於2025-05-23
  • 在JavaScript中如何並發運行異步操作並正確處理錯誤?
    在JavaScript中如何並發運行異步操作並正確處理錯誤?
    同意操作execution 在執行asynchronous操作時,相關的代碼段落會遇到一個問題,當執行asynchronous操作:此實現在啟動下一個操作之前依次等待每個操作的完成。要啟用並發執行,需要進行修改的方法。 第一個解決方案試圖通過獲得每個操作的承諾來解決此問題,然後單獨等待它們: c...
    程式設計 發佈於2025-05-23
  • 為什麼不````''{margin:0; }`始終刪除CSS中的最高邊距?
    為什麼不````''{margin:0; }`始終刪除CSS中的最高邊距?
    在CSS 問題:不正確的代碼: 全球範圍將所有餘量重置為零,如提供的代碼所建議的,可能會導致意外的副作用。解決特定的保證金問題是更建議的。 例如,在提供的示例中,將以下代碼添加到CSS中,將解決餘量問題: body H1 { 保證金頂:-40px; } 此方法更精確,避免了由全局保證金重置...
    程式設計 發佈於2025-05-23
  • 如何使用Regex在PHP中有效地提取括號內的文本
    如何使用Regex在PHP中有效地提取括號內的文本
    php:在括號內提取文本在處理括號內的文本時,找到最有效的解決方案是必不可少的。一種方法是利用PHP的字符串操作函數,如下所示: 作為替代 $ text ='忽略除此之外的一切(text)'; preg_match('#((。 &&& [Regex使用模式來搜索特...
    程式設計 發佈於2025-05-23

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3