Rick and Morty Character Explorer

<% if (data.results && data.results.length > 0) { %> <% data.results.forEach(character => { %> <% }); %>
Image Name Status Species Origin Actions
\\\"Erstellen\\\" 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

\\\"Erstellen\\\" 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"}}
„Wenn ein Arbeiter seine Arbeit gut machen will, muss er zuerst seine Werkzeuge schärfen.“ – Konfuzius, „Die Gespräche des Konfuzius. Lu Linggong“
Titelseite > Programmierung > Erstellen eines Rick and Morty-Charakter-Explorers mit HTMX und Express.js

Erstellen eines Rick and Morty-Charakter-Explorers mit HTMX und Express.js

Veröffentlicht am 09.08.2024
Durchsuche:805

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!

Freigabeerklärung Dieser Artikel ist abgedruckt unter: https://dev.to/mikeyny_zw/building-a-rick-and-morty-character-explorer-with-htmx-and-expressjs-12n3?1 Bei Verstößen wenden Sie sich bitte an Study_golang @163.com löschen
Neuestes Tutorial Mehr>

Haftungsausschluss: Alle bereitgestellten Ressourcen stammen teilweise aus dem Internet. Wenn eine Verletzung Ihres Urheberrechts oder anderer Rechte und Interessen vorliegt, erläutern Sie bitte die detaillierten Gründe und legen Sie einen Nachweis des Urheberrechts oder Ihrer Rechte und Interessen vor und senden Sie ihn dann an die E-Mail-Adresse: [email protected] Wir werden die Angelegenheit so schnell wie möglich für Sie erledigen.

Copyright© 2022 湘ICP备2022001581号-3