Written by: Geoffrey Callaghan

HTML Forms with Eleventy (11ty)

Html Forms With Eleventy (11ty)

To use HTML forms with Eleventy (11ty) and Fabform, you need to follow these steps:

  1. Install Fabform: If you haven’t already, install Fabform via npm:

    npm install fabform
  2. Create a Form Template: In your Eleventy project, create an HTML template for your form. You can use the usual HTML syntax for forms, and you can use Fabform’s directives to enhance it.

  3. Include Fabform: Include Fabform in your project. You can use a module bundler like Webpack or just include it via a <script> tag.

  4. Use Fabform Directives: Within your form template, you can use Fabform’s directives to enhance your form’s functionality. For example:

    <form fab-form name="myForm" action="/submit" method="POST">
        <input type="text" name="name" fab-model="formData.name">
        <button type="submit">Submit</button>
    </form>

    In this example, fab-form directive initializes a Fabform instance, fab-model binds form input to a variable in your script, and fab-validate can be used for form validation.

  5. Handle Form Submission: Handle form submission either through Eleventy’s own data processing methods or through JavaScript. When the form is submitted, you can retrieve the form data and handle it accordingly.

  6. Process Form Data: Once the form is submitted, process the form data on the server-side using Eleventy’s data processing methods or any other backend technology you’re using.

Here’s a basic example of how your Eleventy template might look:

---
layout: layouts/base.njk
title: Contact Form
---
<h1>Contact Us</h1>
<form fab-form name="contactForm" action="/submit" method="POST">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" fab-model="formData.name" required>
    
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" fab-model="formData.email" required>

    <label for="message">Message:</label>
    <textarea id="message" name="message" fab-model="formData.message" required></textarea>
    
    <button type="submit">Submit</button>
</form>

<script src="/path/to/fabform.js"></script>
<script>
    const formData = {};
</script>

In this example, we’re using Nunjucks templating engine for Eleventy. Adjust it according to your chosen templating engine. Also, make sure to include the Fabform JavaScript file (fabform.js) in your project.

Remember, this is just a basic example. You might need to adjust it according to your specific requirements and the capabilities of Fabform.