Twig 和 PHP 的问题
Problems with Twig and PHP
我正在尝试使用 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');
视图代码:
{% 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 不会自动在您的控制器中查找变量。您需要将 approved_articles
等模板变量显式传递到 Twig 渲染引擎中。
附带说明一下,您的 articles.php
模板文件以 .php
扩展名命名,但它实际上不是 PHP 文件。通常模板以 .twig
扩展名命名。
我正在尝试使用 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');
视图代码:
{% 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 不会自动在您的控制器中查找变量。您需要将 approved_articles
等模板变量显式传递到 Twig 渲染引擎中。
附带说明一下,您的 articles.php
模板文件以 .php
扩展名命名,但它实际上不是 PHP 文件。通常模板以 .twig
扩展名命名。