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

Leave a Reply

Your email address will not be published. Required fields are marked *