1

I'm building a php cms and using Twig template engine. I'm now building the news archive page which shows page titles. Before Twig I would have done something like this:

$articles = $db->query("SELECT * FROM `articles` ORDER BY `id` DESC");
while ($article = $articles->fetch_assoc())
{
echo "<a href=\"article.php?id=".$article['id']."\">".$article['title']."</a><br />"
}

How do I do that with Twig?

Naxon
  • 1,354
  • 4
  • 20
  • 40

1 Answers1

2

According to Twig documentation this is a very simple stuff

controller.php from you will do business logic stuff (the C in MVC)

$articles = $db->query("SELECT * FROM `articles` ORDER BY `id` DESC");
$articles_data = [];

while ($article = $articles->fetch_assoc())
        $articles_data[] = $article

$this->render('html.twig', ['articles' => $articles]);

home.twig (the V in MVC)

..
...
{% for article in articles %}
    <a href="article.php?id={{ article.id }}">{{ article.title }}</a>
{% endfor %}
...
..

You should also use a model class (the M in MVC) from which you will handle data example here

Happy coding :D

Community
  • 1
  • 1