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
浏览:775

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]删除
最新教程 更多>
  • 如何限制动态大小的父元素中元素的滚动范围?
    如何限制动态大小的父元素中元素的滚动范围?
    在交互式界面中实现垂直滚动元素的CSS高度限制 考虑一个布局,其中我们具有与可滚动的映射div一起移动的subollable map div用户的垂直滚动,同时保持其与固定侧边栏的对齐方式。但是,地图的滚动无限期扩展,超过了视口的高度,阻止用户访问页面页脚。 可以限制地图的滚动,我们可以利用CSS...
    编程 发布于2025-02-07
  • Java是否允许多种返回类型:仔细研究通用方法?
    Java是否允许多种返回类型:仔细研究通用方法?
    在java中的多个返回类型:一个误解介绍,其中foo是自定义类。该方法声明似乎拥有两种返回类型:列表和E。但是,情况确实如此吗?通用方法:拆开神秘 [方法仅具有单一的返回类型。相反,它采用机制,如钻石符号“ ”。分解方法签名: :本节定义了一个通用类型参数,E。它表示该方法接受了扩展foo类的任...
    编程 发布于2025-02-07
  • 如何在Java列表中有效计算元素的发生?
    如何在Java列表中有效计算元素的发生?
    计数列表中的元素出现在列表 中,在java编程中,列举列表中列举元素出现的任务来自列表。为此,收集框架提供了全面的工具套件。在这种情况下,Batocurrences变量将保持值3,代表动物列表中的“ BAT”出现的数量。 &&& [此方法是简单的,可以得出准确的结果,使其成为计算列表中元素出现的理...
    编程 发布于2025-02-07
  • 可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    &lt;/main&gt; &lt;section&gt; ,但无法使其正常工作,如您所见。任何洞察力都将不胜感激! display:grid; { position:sticky; top:1em; z-index:1 1 ; { { { pos...
    编程 发布于2025-02-07
  • 如何在运行时从类中动态检索属性值?
    如何在运行时从类中动态检索属性值?
    运行时检索属性 本文介绍一种通用的方法,用于动态访问和提取类的属性值。 使用专用方法 定义一个接受类型参数的通用方法: public string GetDomainName<T>() 方法内部: 使用 typeof(T).GetCustomAttributes 检索自定义属性: ...
    编程 发布于2025-02-07
  • 如何使用PHP从XML文件中有效地检索属性值?
    如何使用PHP从XML文件中有效地检索属性值?
    从php 您的目标可能是检索“ varnum”属性值,其中提取数据的传统方法可能会使您感到困惑。 - > attributes()为$ attributeName => $ attributeValue){ echo $ attributeName,'=“',$ at...
    编程 发布于2025-02-07
  • 在没有密码提示的情况下,如何在Ubuntu上安装MySQL?
    在没有密码提示的情况下,如何在Ubuntu上安装MySQL?
    在ubuntu 使用debconf-set-selections sudo debconf-set-selections
    编程 发布于2025-02-07
  • 如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    插入记录时如何解决“一般错误:2006 MySQL 服务器已消失”介绍:将数据插入 MySQL 数据库有时会导致错误“一般错误:2006 MySQL 服务器已消失”。当与服务器的连接丢失时会出现此错误,通常是由于 MySQL 配置中的两个变量之一所致。解决方案:解决此错误的关键是调整wait_tim...
    编程 发布于2025-02-07
  • 版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    在默认值中使用current_timestamp或mysql版本中的current_timestamp或在5.6.5 这种限制源于遗产实现的关注,这些限制需要为Current_timestamp功能提供特定的实现。消息和相关问题 `Productid` int(10)unsigned not ...
    编程 发布于2025-02-07
  • 如何在Java字符串中有效替换多个子字符串?
    如何在Java字符串中有效替换多个子字符串?
    Exploiting Regular ExpressionsA more efficient solution involves leveraging regular expressions.正则表达式允许您定义复杂的搜索模式并在单个操作中执行文本转换。示例示例usage 接下来,您可以使用匹配器...
    编程 发布于2025-02-07
  • 如何克服PHP的功能重新定义限制?
    如何克服PHP的功能重新定义限制?
    克服PHP的函数重新定义限制在PHP中,多次定义一个相同名称的函数是一个no-no。尝试这样做,如提供的代码段所示,将导致可怕的“不能重新列出”错误。 // error:“ coss redeclare foo()” 但是,php工具腰带中有一个隐藏的宝石:runkit扩展。它使您能够灵活地...
    编程 发布于2025-02-07
  • PHP阵列键值异常:了解07和08的好奇情况
    PHP阵列键值异常:了解07和08的好奇情况
    PHP数组键值问题,使用07&08 在给定数月的数组中,键值07和08呈现令人困惑的行为时,就会出现一个不寻常的问题。运行print_r($月份)返回意外结果:键“ 07”丢失,而键“ 08”分配给了9月的值。此问题源于PHP对领先零的解释。当一个数字带有0(例如07或08)的前缀时,PHP将...
    编程 发布于2025-02-07
  • 如何从PHP服务器发送文件?
    如何从PHP服务器发送文件?
    将文件发送到user
    编程 发布于2025-02-07
  • 如何干净地删除匿名JavaScript事件处理程序?
    如何干净地删除匿名JavaScript事件处理程序?
    在这里工作/},false); 不幸的是,答案是否。除非在Creation中存储对处理程序的引用。要解决此问题,请考虑将事件处理程序存储在中心位置,例如页面的主要对象,请考虑将事件处理程序存储在中心位置,否则无法清理匿名事件处理程序。 。这允许在需要时轻松迭代和清洁处理程序。
    编程 发布于2025-02-07
  • 如何使用PHP将斑点(图像)正确插入MySQL?
    如何使用PHP将斑点(图像)正确插入MySQL?
    在尝试将image存储在mysql数据库中时,您可能会遇到一个可能会遇到问题。本指南将提供成功存储您的图像数据的解决方案。 easudy values('$ this-> image_id','file_get_contents($ tmp_image)...
    编程 发布于2025-02-07

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3