Creating a Recipe Website with Ingredient Filtering in Hugo

Creating a recipe website that allows users to filter recipes by ingredients can greatly enhance user experience and engagement. Using Hugo, a fast static site generator, developers can build such a website efficiently with the right approach.

Setting Up Your Hugo Project

Start by creating a new Hugo site with the command:

hugo new site recipe-website

Navigate into your project directory and add a theme or start with a minimal setup. Hugo’s flexibility allows you to customize your site extensively.

Creating Recipe Content

Organize your recipes using content files. For example, create a folder content/recipes and add markdown files for each recipe:

hugo new recipes/spaghetti-carbonara.md

Include front matter with ingredients:

+++
title = "Spaghetti Carbonara"
ingredients = ["spaghetti", "eggs", "parmesan", "bacon", "pepper"]
+++

Implementing Ingredient Filtering

To enable filtering, you can use JavaScript to dynamically show or hide recipes based on selected ingredients. First, list all ingredients as filter options:

<div id="ingredient-filters">
  <button data-ingredient="spaghetti">Spaghetti</button>
  <button data-ingredient="eggs">Eggs</button>
  <button data-ingredient="bacon">Bacon</button>
  <button data-ingredient="parmesan">Parmesan</button>
  <button data-ingredient="pepper">Pepper</button>
</div>

Next, assign data attributes to each recipe card to indicate their ingredients:

<div class="recipe" data-ingredients='["spaghetti","eggs","parmesan","bacon","pepper"]'>
  <h3>Spaghetti Carbonara</h3>
  <p>A classic Italian pasta dish.</p>
</div>

Adding JavaScript for Filtering

Include a script that listens for button clicks and filters recipes accordingly:

<script>
  const buttons = document.querySelectorAll('#ingredient-filters button');
  const recipes = document.querySelectorAll('.recipe');

  buttons.forEach(button => {
    button.addEventListener('click', () => {
      const ingredient = button.getAttribute('data-ingredient');
      recipes.forEach(recipe => {
        const ingredients = JSON.parse(recipe.getAttribute('data-ingredients'));
        if (ingredients.includes(ingredient)) {
          recipe.style.display = '';
        } else {
          recipe.style.display = 'none';
        }
      });
    });
  });
</script>

Final Tips

Enhance your site by adding reset buttons, multiple ingredient filters, or even search functionality. Using Hugo’s static site capabilities, combined with JavaScript, provides a fast and interactive user experience for your recipe website.