获取PHP传递的JS中的树枝变量

时间:2018-08-08 01:39:03

标签: php twig

我在

中有以下代码

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

0 个答案:

没有答案