How to check if specific key array element exists? - php

i have my view in twig
and i have an array which has or hasnt key value i need how to check it if its exist ?
example {{ weather.wind.deg }} and for current moment its possible there is no wind deg so the weather.wind array will not contain an element witch key deg
how to check it if it has it or no ?
maybe i should do it before i past this to my view ?
somewhere here ?
$app->get('/', function () use ($app) {
return $app['twig']->render('index.html.twig', array(
'weather' => $app['weather_service']->get($app['location_service']->get()),
'location' => $app['location_service']->get())
);
});

In you twig template you can do :
{% if weather.wind.deg is defined %}
make your things
{% endif %}

Related

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') }}

Twig - Use variable key for object

I am using Twig and I have a problem.
I have a problem when I want to use a variable index for an object.
Here is my code:
{% for label, field in params.fields %}
{{ dump(data.field) }}
{% endfor %}
data is an object containing {'email': 'test#test.fr', 'name': 'John'}.
Field is an array of string containing ['email', 'name']
I can't show the value my object dynamically.
{{ dump(data.email) }} works.
How can I use dynamic indexes?
In Twig syntax, data.field is equal to $data['field'] in PHP. In other words, Twig use field as the array key name instead of taking the value of the field variable and use it as a key name.
If you want something similar to $data[$field], you can use the attribute() function:
The attribute function can be used to access a "dynamic" attribute of a variable:
Example:
{{ dump(attribute(data, field)) }}
{# or simply #}
{{ attribute(data, field) }}

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

Symfony2 Array to string conversion, set empty value

I`am rendering a twig template in symfony2 and its possible to get a variable with value of array type but i am trying to preview the variable and this error pops:
Array to string conversion ...
So my qustion is not how to print out the array, but is it possible in twig to disable this error, so when an array comes and it cannot be outputed, to set an empty value.
In config.yml, under twig i have set
strict_variables: false
But this dose not include printing arrays.
EDIT:
In controller I pass this array to twig, for example:
'data' => array(
'description' => array(
'desc1',
'desc2'
)
);
In twig I am trying to print {{ data['description'] }} and I got the following error:
Array to string conversion ...
This is the normal error that must pop, but I need if I try to print this a no error to pop but instead I need to print nothing(empty value), same way like trying to print an non existing variable with twig set with
strict_variables: false
ANSWER:
Make a custom function:
public function getFunctions()
{
return array(
'to_string' => new \Twig_Function_Method($this, 'toString')
);
}
public function toString($data) {
if(is_array($data)) {
return '';
}
return $data;
}
And in twig template:
{{ to_string(data['description']) }}
You have two desc: desc1 and desc2, what do you want to print? If both you have to use this notation (for instance)
{{ data['description'][desc1] }} - {{ data['description'][desc2] }}
More in general:
{% for desc in data['description'] %}
{{ desc }}
{% endfor %}
EDIT
Ok, now I got it (from your comment):
{% if data['description'] is iterable %}
//echo here an empty string
{% else %}
{{ data['description'] }}
{% endif %}

can't access property of stdClass in TWIG

I have googled around and it seems as though the creators of TWIG really insists that what I am doing here, which is to me a pure job for the VIEW, something that the template shouldn't take care of at all?!
I know I can't iterate over an object of stdClass without some custom TWIg filters, so I hacked that for now, but if I can't eve access properties dynamically this TWIG thing really isn't very useful at all.
$fixedModuleNames = array('time', 'date', 'weather'); //since TWIG doesn't iterate over objects by default, this is my solution, don't feel like adding a bunch of twigfilters just for this.
$fixedModules = json_decode($entity->getFixedModules());
/*
Here's what fixedModules look like (although here not JSON but array, before encoded to json, I like to create my JSONs this way in PHP)
$fixedModules["time"] = array(
'show' => true,
'left' => 10,
'top' => 10,
'width' => 100,
'height' => 200,
'fontColor' => '#000000',
'fontSize' => 40,
'fontFamily' => 'Arial',
'borderColor' => '',
'borderRounding'=> 0,
'bgColor' => ''
);
*/
Here's what I am trying to do...
{% for item in fixedModuleNames %}
<TR>
<TD><input type="number" id="left_{{ item }}" value="{{ fixedModules[item].left }}" class="LayoutModuleEditField" /></TD>
So this line fails
{{ fixedModules[item].left }}
There must be a way around this since what I am doing is very routine?
Ah, is this perhaps the preferred way of doing it?
{{ attribute(fixedModules, item).left }}
If your attribute function works then use it.
Consider however fixedModules[item].left. You are asking twig to figure out that item is a variable while left is a constant. Difficult for any system to do to say the least.
I would use something like:
{% for moduleName, module in fixedModules %} {# Time, Date, Weather module #}
{% for itemName,itemValue in module %} {# Process each attribute in the module #}
...
If you want to iterate over an object then just implement the array iterator interface. Usually pretty simple.
item is not the key, but an element of your array. So you can access your attributes this way:
{% for item in fixedModuleNames %}
left = {{ item.left }}
{% enfor %}
If you really want to use the key instead, do something like:
{% for key, item in fixedModuleNames %}
left = {{ fixedModuleNames[key].left }}
{% enfor %}
Hope this helps.

Categories