J
J
Jesse Pinkman2021-01-08 13:24:59
PHP
Jesse Pinkman, 2021-01-08 13:24:59

How to correctly display different templates on the page?

There is a table with products, which has the following structure:

|ID       |NAME            |COUNT        |PROVIDER          |DATEOFPURCHASE      |CATEGORY          
|1        |Банан           |20           |Иван              |2007-01-01          |Fruits
|2        |Помидор         |500          |                  |2001-01-01          |Vegetables
|1        |Телефон         |2            |Альбинос          |                    |Phone


I make a request to the database and display products with the selected category

$category = $_POST['category'];
    $stock_list = [];
    $stock_view = $dbpdo->prepare("SELECT * FROM products 
                                   WHERE count > 0 
                                   AND category = ?
                                   ORDER BY id DESC");
    $stock_view->execute([$category]);
    if($stock_view->rowCount()>0) {
        while ($row = $stock_view->fetch(PDO::FETCH_BOTH)) {
        //заполняю массив
        $stock_list[] = [
                'id' => $row['id'],
                'name' => $row['name'],
                'count' =>  $row['count'],
                'provider' => $row['provider'],
                'date' => $row['DATEOFPURCHASE']
            ]; 

       }

      //далее отправляю массив в шаблон
       echo $tpl = $twig->render('page/tpl.twig', $stock_list);
    }


Now with what I have a problem. For example, I have given only a few columns and categories here, but in fact there are more of them and, depending on the product category, a table is displayed, for example, for Vegetables, the provider column does not need to be displayed, but for fruits it is necessary, and also for phones you do not need DATEOFPURCHASE and for the rest need. The only option that came to my mind is to make a template for each category in twig and check the category with if-mi and display the desired block. But it seems to me that this option is terrible and there is clearly a better solution. It could be done ifami, if there were only 2-3 categories, then it’s not critical to make a couple of templates and pages, but a couple of months ago there were 5 categories and now 30, I’m not sure that in a year there won’t be 200 and I think I’ll write my own template for each not the best option. How can this be automated

Please help me solve this problem, I will be grateful. Any information on the topic would be helpful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoriHagen, 2021-01-11
@BoriHagen

As an option, write a single template for output, with different conditions in which the category is checked and, depending on this, something is displayed - and something is ignored. The main thing is without code duplication.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question