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;
}
}