我正在尝试使用 Twig 和 PHP 创建一个内容管理系统,但是当我打开页面时,它说没有条目。我已经使用 var_dump()
验证了这一点。
路线代码:
$app->get('/articles', function() use ($app) {
$approved_articles = $db_bsa->query("
SELECT id, label, slug
FROM approved_articles
")->fetchAll(PDO::FETCH_ASSOC);
var_dump($approved_articles);
$app->render('main/articles.php');
})->name('articles');
View 代码:
{% extends 'templates/default.php' %}
{% block title %}Articles{% endblock %}
{% block content %}
<article class="article">
<header>
<h2>Articles</h2>
</header>
<footer>
<p class="post-info">A Directory Style Listing of our Active Articles</p>
</footer>
{% if approved_articles %}
<ul>
{% for approved_article in approved_articles %}
<li>{{ approved_article.label }}</li>
{% endfor %}
</ul>
{% else %}
<p>No articles at the moment...</p>
{% endif %}
</article>
{% endblock %}
此外,这里还发布了一条更长的链,其中包含更多背景信息:https://www.codecourse.com/forum/topics/problems-using-twig-and-php/329
感谢您的帮助!
最佳答案
渲染模板时,您需要将 approved_articles
传递给 twig。
$app->render('main/articles.php', array('approved_articles' => $approved_articles));
Twig 不会自动在 Controller 中查找变量。您需要将 approved_articles
等模板变量显式传递到 Twig 渲染引擎中。
顺便说一句,您的 articles.php
模板文件以 .php
扩展名命名,但它实际上并不是 PHP 文件。通常模板以 .twig
扩展名命名。
关于php - Twig 和 PHP 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31976984/