dsceme82487 2015-08-12 23:16
浏览 26
已采纳

Twig和PHP的问题

I am trying to create a content management system using Twig and PHP, but when I open the page, it says that there are no entries when there are. I have verified this using a var_dump().

Code for the route:

$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');

Code for the 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 %}

Also, a longer chain with more background info is posted here: https://www.codecourse.com/forum/topics/problems-using-twig-and-php/329

Thanks for the help!

  • 写回答

1条回答 默认 最新

  • doushi9780 2015-08-12 23:26
    关注

    You need to pass approved_articles to twig when you render the template.

    $app->render('main/articles.php', array('approved_articles' => $approved_articles));
    

    Twig doesn't automatically find variables in your controller. You need to explicitly pass template variables like approved_articles into the Twig rendering engine.

    As a side note, your articles.php template file is named with a .php extension, but it is not actually a PHP file. Usually templates are named with a .twig extension.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵