Adding PhotoSwipe to Your Project
PhotoSwipe is a popular JavaScript library designed to create responsive and accessible image galleries. Here is a detailed guide on how to integrate PhotoSwipe into your project.
Step 1: Installing PhotoSwipe
Start by installing the PhotoSwipe package using npm. Open your terminal and execute the following command:
npm install photoswipe
Alternatively, you can fetch the necessary files from the repository.
Step 2: Copying Necessary Files
After installation, you need to manually copy the PhotoSwipe files from the node_modules/photoswipe/dist
folder to the static
directory of your project. This step ensures the correct placement of the required scripts and style sheets in your web environment.
├── static
│ ├── css
│ │ └── photoswipe.css
│ └── photoswipe
│ ├── photoswipe-lightbox.esm.js
│ ├── photoswipe-lightbox.esm.js.map
│ ├── photoswipe-lightbox.esm.min.js
│ ├── photoswipe.esm.js
│ ├── photoswipe.esm.js.map
│ └── photoswipe.esm.min.js
Step 3: Adding CSS and Initializing the Library
Integrate the PhotoSwipe CSS and JavaScript files into your project. This can be done by adding links to the photoswipe.css
and photoswipe-lightbox.esm.js
files in your HTML documents or through your project’s build process.
<link rel="stylesheet" href="/css/photoswipe.css" />
To activate PhotoSwipe, add the following initialization script just before the closing </body>
tag in your HTML file:
<script type="module">
console.log("uihio");
import PhotoSwipeLightbox from "/photoswipe/photoswipe-lightbox.esm.js";
const lightbox = new PhotoSwipeLightbox({
gallery: "#my-gallery",
children: "a",
initialZoomLevel: "fit", // initial zoomlevel
secondaryZoomLevel: "fit", // don't change zoom
imageClickAction: "close", // close on click
pswpModule: () => import("/photoswipe/photoswipe.esm.js"),
});
lightbox.init();
</script>
Step 4: Creating a Shortcode for Easy Integration
For projects using static site generators such as Hugo, create a shortcode to simplify the addition of galleries and make them more versatile.
Navigate to your layouts directory and create a gallery.html
file inside layout/shortcodes/
:
layouts
├── _defaults
│ ├── kbdfsjjh.html
│ └── single.html
├── partials
│ ├── extend_body.html
│ ├── extend_footer.html
│ └── extend_head.html
└── shortcodes
├── desc.html
└── gallery.html
The content of gallery.html
should look like this:
<!-- block begin -->
<div id="my-gallery">
{{ $images := .Page.Resources.Match (printf "%s*" (.Get "folder")) }} {{ range
$images }}
<a
href="{{ .RelPermalink }}"
data-pswp-width="{{ .Width }}"
data-pswp-height="{{ .Height }}"
>
<img src="{{ .RelPermalink }}" alt="{{ .Name }}" />
</a>
{{ end }}
</div>
<!-- end of block -->
<!-- caption code -->
{{ with .Get "title" }}
<h4>{{ . }}</h4>
{{ end }}
Use the shortcode in your content as follows:
{{< gallery folder="folder_with_images" title="My favorite cat" >}}
The result: