1

I have the following code in

index.php

// Render the homepage
$twig = new Twig_Environment(new Twig_Loader_Filesystem(__DIR__.'/src/templates'));
$twig->display('homepage.twig', array('books' => $books));

Here book entry is like this

new Book('Finnegans Wake', 'Janes Joyce', 'English', 1941);

Then, inside my homepage.twig, I have the following:

<h1> {{ books[0].language   }} </h1> //English is printed correctly
<script>
    console.log("{{ books|json_encode }}");
</script>

Here, the above console.log prints an empty array like the following:

[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]

How can I access the books arrays in JS, which is passed from PHP to twig?

Books class

class Book
{
    private $title = '';
    private $author = '';
    private $language = '';
    private $year = 1970;

    public function __construct($title, $author, $language, $year)
    {
        $this->title = $title;
        $this->author = $author;
        $this->language = $language;
        $this->year = $year;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @return string
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * @return string
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * @return int
     */
    public function getYear()
    {
        return $this->year;
    }
}
kosta
  • 4,302
  • 10
  • 50
  • 104
  • https://stackoverflow.com/questions/13928729/use-javascript-to-access-a-variable-passed-through-twig – Shivang Agarwal Aug 08 '18 at 01:45
  • It might be helpful for us to see the code for the `Book` class. – msbit Aug 08 '18 at 03:45
  • @msbit I added the `Book` class – kosta Aug 08 '18 at 04:35
  • Thanks @user3288346. So I think there are two things that you'll need to do here: add `|raw` to `books|json_encode` (so making it `books|json_encode|raw`) as mentioned in the question linked to by @shivang-agarwal, and make any class fields you want exposed `public`, as that's what `json_encode` picks up. The first will be needed when you want to actually use the JSON later, the second when you want the JSON to have the object contents. – msbit Aug 08 '18 at 06:53

0 Answers0