0

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.

11
  • 1) $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. Commented Mar 25, 2020 at 18:45
  • @El_Vanja Sorry, I meant JSON encoded string, not an object. As for 2), it's the standard Twig syntax I followed from: twig.symfony.com/doc/3.x/api.html Commented Mar 25, 2020 at 19:04
  • Yes, but you're not in Twig there, you're in PHP. You're not getting a syntax error? There should be quotes around that value for it to work. Commented Mar 25, 2020 at 19:06
  • 1
    just a side note, make sure that json_img consist the right data before parsing it, just debug it with a console.log because what sometimes happens to me is that I get this error message because of a typo in my PHP script which typo turns the entire encoded data into a non-json text and json.parse don't want to parse anything that it is not familiar with Commented Mar 25, 2020 at 19:20
  • 1
    @imaginois Is correct you can't use twig vars inside external files. Workaround here Commented Mar 26, 2020 at 8:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.