Twig - getting text filed key and value - php

I hav text filed where I stored some json data.
I am getting in my twig template on dump like:
"{"birthDate":"2021-09-01", "amount":8}"
I want to access keys so I can extract it's values.
Tried with json_encode or:
{% for key, value in item.value %}
but nothing seems to work.
Is the problem with the output data?

It seems that your item is neither object nor array it seems to be a string.
Try to convert your data to object or array json as below:
$objJson = json_decode($yourDBArray['menu']);
$arrJson = json_decode($yourDBArray['menu'],true);
Then you can use to show as below
{% for key,value in menu %}
Key : {{ key }}
Value : {{ value }}
{% 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 pass query url parameter to a twig template

I am trying to pass query string parameters through my url to a node twig template (node--template.html.twig) I have tried
{% set queryParams = app.request.query.all %}
However, nothing is showing when passed.
You are almost there.
{% set queryParams = app.request.query.all %}
This statement will not show anything. Because it is only supposed to assign query variables array to queryParams
If you want to display, you have multiple ways after the above statement.
For example, if you just want to display the value of user_id query variable from URL.
{% set queryParams = app.request.query.all %}
{{ queryParams["user_id"] }}
Another example, if you want to loop through all query variables:
{% set queryParams = app.request.query.all %}
{% for key, value in queryParams %}
{{ key }} => {{ value }}
{% endfor %}

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

Name of Twig variable in a Twig variable

I get a list of collections right from Doctrine and I store them into an array.
For example:
$data['collList'] = $heyDoctrine->giveMeMyColls();
But I also want to retrieve some informations about these collections.
I store it into $data['collectionId'].
Until this point, everything works fine.
But in my Twig template, I want to create ordered lists with the name of my collection and every item of this list would be an information about this collection.
So, in PHP, I would do this:
foreach($data['collList'] as $collItem){
echo $collItem['name'];
echo '<ul>';
foreach($data[$collItem['id']] as $collItemData){
echo '<li>'.$collItemData.'</li>';
}
}
My problem is: how to do this with Twig?
I don't know how to say to Twig «hey, use «coll.id» as THE NAME of an other variable!
I've looked a bit and I've found the «attribute» function, but I wasn't able to make it work.
How should I do that?
Thanks a lot.
So, try next twig code:
{% for key, collItem in data.collList %}
{{ collItem.name }}
<ul>
{% for collItemData in data[collItem.key] if key == 'id' %}
<li> {{ collItemData }} </li>
{% endfor %}
</ul>
{% endfor %}

Twig Array to string conversion

This is probably relatively easy to do, but I'm new to twig and I'm frustrated.
I'm adapting code from this answer: https://stackoverflow.com/a/24058447
the array is made in PHP through this format:
$link[] = array(
'link' => 'http://example.org',
'title' => 'Link Title',
'display' => 'Text to display',
);
Then through twig, I add html to it, before imploding:
<ul class="conr">
<li><span>{{ lang_common['Topic searches'] }}
{% set info = [] %}
{% for status in status_info %}
{% set info = info|merge(['{{ status[\'display\'] }}']) %}
{% endfor %}
{{ [info]|join(' | ') }}
</ul>
But I'm getting:
Errno [8] Array to string conversion in
F:\localhost\www\twig\include\lib\Twig\Extension\Core.php on line 832
It's fixed when I remove this line, but does not display:
{{ [info]|join(' | ') }}
Any ideas how I can implode this properly?
** update **
Using Twig's dump function it returns nothing. It seems it's not even loading it into the array in the first place. How can I load info into a new array.
info is an array, so you should simple write
{{ info|join(', ') }}
to display your info array.
[info] is a array with one value : the array info.
You shouldn't really be building complex data structures inside of Twig templates. You can achieve the desired result in a more idiomatic and readable way like this:
{% for status in status_info %}
{{ status.display }}
{% if not loop.last %}|{% endif %}
{% endfor %}
You can user json_encode for serialize array as strig, then show pretty - build in twig
{{ array|json_encode(constant('JSON_PRETTY_PRINT')) }}
if need associative array:
{{info|json_encode(constant('JSON_PRETTY_PRINT'))|raw}}

Categories