Twig - Loop returns only 1 result - php

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 %}

Related

timber/twig how to pass `posts` php-object to JavaScript? Some values are lost

When I'm trying to pass the information contained in {{posts}} I cannot retrieve all of it, at least not the post.link information
{% for post in posts %}
<script>
var t = JSON.parse('{{post|json_encode(constant('JSON_HEX_APOS'))|e('js')}}')
t.link = '{{post.link}}'
console.log(t)
</script>
{% endfor %}
Without manually adding the link, it doesn't show up
Why is this happening and how could I workaround this?
EDIT: related https://github.com/timber/timber/issues/1434
You shouldn’t encode your whole post object. You should encode all the values you need separately.
The link for your post doesn’t show up, because link is not a property, but a method of the Timber\Post object. This might be a little bit confusing, because in Twig we use {{ post.link }}. It looks like it’s a property or maybe an array item. But we could also use {{ post.link() }}, which is the same as {{ post.link }}. You can read more about this in the Variables section in Twig for Template Designers.
So what I would do is build a new array with the data you need and encode it to JSON in PHP with wp_json_encode().
PHP
$posts_json = [];
foreach ( $posts as $post ) {
$posts_json[] = wp_json_encode( [
'title' => $post->title(),
'link' => $post->link(),
] );
}
$context['posts_json'] = $posts_json;
By only adding the data you need, you keep the output in the frontend small. Otherwise, you would end up with a lot of data that you will never and that only increases the page size unnecessarily.
And then in Twig, you could do it like this:
{% for post in posts_json %}
<script>
var t = {{ post }}
console.log(t)
</script>
{% endfor %}

How to remove session which contain table?

$tab=array("hello", "world");
if(!$session->has('session_val')) $session->set('session_val', $tab);
How can I remove all values of this session in twig file?
I have tried this:
{{ app.session.remove('session_val') }}
And I have an exception: Array to string conversion
You need to use flash() :-
{{ app.session.flash('session_val') }}
Or:-
{% set tmp = app.session.remove('session_val') %}
Recomendation:- As other suggested thattwig is not the right place to do so. it's for representation not for businness logic execution. Do it inside controller.

How can I set the route parameter name using a variable in Twig?

I am trying to use the url Twig function with Silex to generate a route, but when I use the variable name that I have passed to the template it generates a warning that I have not supplied the parameter.
This is the array I am passing to the template:
[
"total_pages" => $pages,
"current_page" => $page,
"route_name" => "gallery_album",
"route_parameter" => "groupname",
"route_value" => $groupname
]
And in the template I am trying to use:
{{ url(route_name, {route_parameter: route_value, 'page': page} ) }}
(The page variable value is worked out in the template)
This is part of a pagination template that I am building so I need the parameter to be a variable so it can be applied to different pages. This is the error I get when I run this:
I feel this is something that is very simple, I am just missing something fundamental.
It thinks that route_parameter is a string key name and not a variable:
You can do for example:
{% set params = {'page': page, (route_parameter): route_value } %}
{{ url(route_name, params) }}
You can use {{ app->path}} or {{ app->url }}
if you using Silex\Application\UrlGeneratorTrait in you Application class
or alternative using this
{{ app.url_generator.generate('homepage') }}

Empty search results Laravel 4

I am making a simple search engine in which, If the selected list from the dropdown would match with the one inside the 'destinationto' column from the database then it would fetch all the items inside that row. But when I hit the find button, it would not return any item from the database. It would be giving me an empty array.
object(Illuminate\Database\Eloquent\Collection)[141]
protected 'items' =>
array (size=0)
empty
What have I done wrong?
Here are the snippets
OnewayflightControllers.php:
public function onewayflightresults()
{
$destinationto = Input::get('destinationto');
$results = Oneways::where('destinationto','=',$destinationto)->get();
var_dump($results);
}
public function onewayflight()
{
$onewaysfrom = DB::table('oneways')->distinct()->lists('destinationfrom');
$onewaysto = DB::table('oneways')->distinct()->lists('destinationto');
return View::make('content.onewayflight')->with(['destinationfrom'=>$onewaysfrom,'destinationto'=>$onewaysto]);
}
onewayflight.blade.php:
{{ Form::label('destinationto','To: ') }}
{{ Form::select('destinationto', $destinationto)}}
It's only a guess but you should make sure you have only one form element with name destinationto
If you have in form for example
{{ Form::label('destinationto','From: ') }}
{{ Form::select('destinationto', $destinationfrom)}}
{{ Form::label('destinationto','To: ') }}
{{ Form::select('destinationto', $destinationto)}}
If you think it's ok, you should add var_dump($destinationto); to your function to make sure value is what you expect
EDIT
I thought select will use values as keys but it's not so you should probably do something like that:
$onewaysfrom = DB::table('oneways')->distinct()->lists('destinationfrom','destinationfrom');
$onewaysto = DB::table('oneways')->distinct()->lists('destinationto','destinationto');
and not:
$onewaysfrom = DB::table('oneways')->distinct()->lists('destinationfrom');
$onewaysto = DB::table('oneways')->distinct()->lists('destinationto');

What am I typing wrong in this simple PHP Twig program?

What am I typing wrong here? I want to print out a string that says "LarryMoeCurly"
I assume that if I feed an array to the template engine it can access it in the 'users' loop.
-- CODE
$template = $twig->loadTemplate('gen_form.html');
$users = array("Larry", "Moe", "Curly");
echo $template->render($users);
-- TEMPLATE (gen_form.html)
{% for user in users %}
{{ user }}
{% endfor %}
Try this one:
echo $template->render(array('users' => $users));
In your case $users - it is just a name of your variable containing array like ["Larry", "Moe", "Curly"]. So there is no key 'users' in it.

Categories