I'm trying to create a gallery just using Twig and Javascript. First of all, I have a functions that returnsa JSON object of the database values of the images.
In event.php file, I do the following:
$gallery_img = $bdclass->getImages() // JSON_encode
echo $twig->render('event.html', ['gallery' => $gallery_img]);
In event.html I import the following Javascript file:
var json_img = '{{ gallery }}' // Twig's variable containing JSON
const IMG = JSON.parse(json_img) // Line 2
var current = 0
function previous() {
if(current <= 0) {
current = IMG.length - 1
}
else {
current--
}
document.getElementById("event-img").src = IMG[current]
}
function next() {
current = (current + 1) % IMG.length
document.getElementById("event-img").src = IMG[current]
}
I'm getting the following error in the console:
Unexpected token { in JSON at position 1 at JSON.parse () at gallery.js:2
I've checked using echo() that the object is returned as a JSON object server-ide (in event.php), but I can't get Twig and Javascript to work. Any help is appreciated.
$gallery_img = $bdclass->getImages() // JSON Object- PHP does not hold JSON objects. It can either be a JSON encoded string or an object that can be encoded. So which is it? 2)$twig->render(event.html- this looks like PHP and Javascript syntax mixed up.twigvars inside external files. Workaround here