我试图在构造函数中初始化Twig,但遇到了以下问题:
Fatal error: Uncaught Twig\Error\SyntaxError: Unknown "for" tag. Did you mean "for"?
这是我班的样子:
require_once(__DIR__ . '/vendor/autoload.php');
class Test {
public $loader;
public $twig;
public function __construct() {
$this->loader = new Twig_Loader_Filesystem(__DIR__ . '/templates');
$this->twig = new Twig_Environment($this->loader);
$this->show_page();
}
public function show_page() {
$results = get_results_from_db();
$template = $this->twig->loadTemplate('results.twig');
$template->render([
'results' => $results,
]);
}
}
results.twig
{% for result in results %}
<p>{{ result.name }}</p>
{% endfor %}
现在,如果我在构造函数之外删除加载器和twig定义,然后将它们放入show_page
方法中,则效果很好,但这不是Twig的使用方式。
答案 0 :(得分:1)
根据twig documentation,渲染视图时需要回显视图。这应该可以正常工作:
require_once('vendor/autoload.php');
class Test {
public $loader;
public $twig;
public function __construct() {
$this->loader = new Twig_Loader_Filesystem(__DIR__ . '/templates');
$this->twig = new Twig_Environment($this->loader);
$this->show_page();
}
public function show_page() {
$results = get_results_from_db();
$template = $this->twig->loadTemplate('results.twig');
echo $template->render([
'results' => $results,
]);
}
}