我在
中有以下代码index.php
// Render the homepage
$twig = new Twig_Environment(new Twig_Loader_Filesystem(__DIR__.'/src/templates'));
$twig->display('homepage.twig', array('books' => $books));
这里的书名是这样的
new Book('Finnegans Wake', 'Janes Joyce', 'English', 1941);
然后,在我的homepage.twig
中,我有以下内容:
<h1> {{ books[0].language }} </h1> //English is printed correctly
<script>
console.log("{{ books|json_encode }}");
</script>
在这里,上面的console.log打印一个空数组,如下所示:
[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]
如何访问从PHP传递到树枝的JS中的books数组?
图书课
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;
}
}