I am building a custom module for Joomla. Let's call the module "mod_mygallery".
Inside the module I have a the files mod_mygallery.php
, helper.php
and mod_mygallery.xml
.
And off course I also have the tmpl/default.php
file.
Since I am still pretty new at building my own components and modules, I would like some input on how to deal with JavaScript and jQuery inside the template php file.
I am trying to keep my tmpl file as clean as possible. Adding stylesheets, scripts and declaring php vars is all done inside the main mod_mygallery.php file, with some help from my helper class in helper.php.
The module works fine as it is. But I wonder what is best practice to add some jQuery on document ready. Currently, I have declare a JS variable that gets an object from php. On document ready the object is used to initialize my gallery (using light gallery). This is my tmpl/default.php:
<?php
defined('_JEXEC') or die;
?>
<div id="gallery" class="gallery">
<?php echo $images; ?>
</div>
<script type="text/javascript">
const gallerySettings = <?php echo json_encode($gallerySettings, JSON_PRETTY_PRINT); ?>;
jQuery(document).ready(function() {
jQuery("#gallery").lightGallery(
gallerySettings
);
});
</script>
Is this good practice? How would you do it? I would prefer to also keep my JS outside of the template file, but I'm not sure how. Or am I overthinking it?
Thanks for any insights on this.
gallerySettings
constant. just echo the json directly intolightGallery()
. Essentially, I'm advising to avoid declaring "single-use" variables/constants.lightgallery()
. But the json did not render, and as a result the gallery did not work. I assumed this is because php parsed before the document is ready. By asigning it to a var before using it in document ready, it works.<script type="text/javascript"> jQuery(document).ready(function() { jQuery("#gallery").lightGallery(<?php echo json_encode($gallerySettings, JSON_PRETTY_PRINT); ?>); }); </script>
...it does the same thing without the constant needing to be declared.