简体   繁体   中英

Twig - Loop returns only 1 result

i'm trying to make a loop in php while using twig and inside this loop, i am creating a parameter which contains the record from the database query.

The problem is that when I use the parameter in my HTML file, it only return 1 record from the while loop, even if there are 3 or 4 or even more..

This is the php code I have:

public function getWidgetsByName($name)
{
     global $params;
     $get = $this->db->query("SELECT * FROM profile_items
                              WHERE category = 'widget'
                              AND username = '". $name ."'");
     if($get)
     {
          while($key = $get->fetch())
          {
               $params["profile_widget_name"] = $key['name'];
          }
     }
}

And this is the HTML parameter in my HTML twig rendered file:

{{ profile_widget_name }}

The paremeters just get rendered how they are supposed to be rendered:

echo $twig->render('app/views/'. $_REQUEST['p'] .'.html', $params);

And yes the $params variable is an array, in the config it file it first gets used as $params = array("..." => "..."); and I add things to this array by doing $params["..."] = "...";

So, I hope someone can help me.

Thanks in advance, Best Regards.

At the moment, the value of $params["profile_widget_name"] is just one string. Every time you go through the while loop, you overwrite the previous value of the key with the current value.

So when you pass $params to Twig, the value of profile_widget_name is the value of name in the last row of the database to be selected.

I think what you want instead is for the value of profile_widget_name to be an array. Then every time you go through the loop, the current value of name is added to the array, instead of overwriting it.

You do this by doing something like:

$params["profile_widget_names"][] = $key['name'];

Now in your Twig template, you'll need to do something like:

{% for profile_widget_name in profile_widget_names %}
  {{ profile_widget_name }}
{% endfor %}

Using Multiple Parameters

If you want multiple parameters to be on there, you can do this:

$params["profile_widgets"][] = [
    'pos_x' => $key['pos_x'],
    'name'  => $key['name'],
];

And in Twig:

{% for profile_widget in profile_widgets %}
  Name: {{ profile_widget.name }}
  Pos X: {{ profile_widget.pos_x }}
{% endfor %}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM