Search code examples
javascripttwigcraftcms

Dynamic path for images in javascript with lightgallery plugin


I'm working on a project in craft cms and I want to make a gallery block that is added as an entry in craft. After doing some research I was trying to do it with dynamic mode of lightgallery plugin. The problem is that in dynamic mode, both sources and thumbnails for the gallery are defined in javascript, as an ex.

$(document).ready(function () {
  $(".dynamic").on("click", function (e) {
    $(document).lightGallery({
      dynamic: true,
      dynamicEl: [
        {
          src: "",
          thumb: ""
        },
        {
          src: "",
          thumb: ""
        }
      ]

Until now when I was doing galleries with this plugin I was using html structure and for loops in twig like this :

{% for image in entry.xxxx.all() %}
  <a href="{{image.url}}">
     <img src="{{image.url}}">
   </a>
{% endfor %}

Link to codepen for you to get some image of the idea https://codepen.io/Snopek/pen/zYwNxgL

Any ideas how to fit these two together?

Thx for help


Solution

  • You will need to pass the list of images to JavaScript in order to access it in your lightbox initialization function. There are multiple ways to do that. For example, you could use the {% js %} tag to add some JavaScript code to your page that contains the encoded data. Or use the json_encode filter to add the data to your HTML element as a data attribute and use JSON.parse in your JavaScript code to parse the encoded JSON-string.

    Here's a good article on passing data from Twig to JavaScript.