How to Use Alpine.js In Django

In this section we will see how to use Alpine.js in Django framework.

How to Install Tailwind CSS 3 in Django

Step by Step How to Add Tailwind CSS 3 to Django 5

Install Alpine.js Via CDN

You can include Alpine.js in your project by adding the CDN link to your HTML file.

<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>

Integrate Alpine.js with Django Template

In your Django template (HTML file), you can start using Alpine.js directives.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Django + Alpine.js App</title>
  <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
</head>

<body>
  <div x-data="{ isOpen: false }">
    <button @click="isOpen = !isOpen">Toggle Content</button>
    <div x-show="isOpen">
      <!-- Your content here -->
      <p>This is some dynamic content!</p>
    </div>
  </div>
</body>

</html>
alpine.js In django

Serve the Django Application.

python manage.py runserver
Saim

Hi there! My name is Saim and I’m excited to dive headfirst into the world of Python Django. I’m eager to learn and grow every step of the way, and I’ll be documenting my journey through blog posts. I’ll share the highs, lows, and everything in between with you. Together, let’s uncover the wonders of Python Django and its endless possibilities in web development.

Facebook | Twitter X | DEV