Twig: Automatically convert json string to array - php

it's possible to automaticaly convert JSON string variable to array in Twig?
I can use for example this code:
{item.id}
{set array = item.parameters|json_encode()} <-- can i do this automatically for json formatted strings?
{% for parameter in array %}
...
{% endfor %}
But users will write own templates in admin (XML output from e-shop) so I want as few things to learn and understand the code writing. So it's possible to check all variables for JSON syntax and convert to array automaticaly?
Data will be generated from MySQL database directly to template, so there is no controller for between DB result and Twig. I also can't use JSON_TYPE in MySQL because we use old version.
Also i don't looking for something like this (or cusom filter):
{item.id}
{% for parameter in item.parameters|json_encode() %}
...
{% endfor %}
My idea is this:
{item.id}
{% for parameter in item.parameters %}
...
{% endfor %}
(So if there is autoescape in Twig, I am looking for "auto_json_decode" :-) )

Related

Build valid json object in Twig

So I'm trying to build a JSON object in a Twig template and ran into some issues.
Responding to a POST request with something like this from a Twig works fine:
{"urls": ["/a","/b"]}
However if there's invalid json for example a trailing comma, like this;
{"urls": ["/a","/b",,,,,]}
then javascript complains when it receives it (which makes sense as it's invalid).
Doing something like this will always result in invalid JSON because of the trailing comma:
{"urls": [
{% for i in objects %}
"/img/example/'~i.get_url()",
{% endfor %}
]}
Question:
So how do you use Twig to loop over an array of objects and build a valid JSON object?
You can check if is the last loop iteration with the standard cycle twig variable, as example:
{"urls": [
{% for i in objects %}
"/img/example/'{{i.get_url()}}"{% if not loop.last %} , {%endif%}
{% endfor %}
]}
Check this working example
Hope this help
You could create a custom twig filter and output it on the page like :
{{ objects |obj2Json }}
In the filter you could just json_encode the object.
https://symfony.com/doc/current/templating/twig_extension.html

Twig iterate/read and get value - Octobercms

Hi guys its rather a very basic question, had chance to look several questions on stackoverflow but all in vain.
so i have this twig variable called "WordoftheDayfromDB ", to which i am passing from some data after querying DB in my controller via laravel pluck method. The controller exsits in plugin of octobercms. the content of the variable is shown below
{% set WordoftheDayfromDB = __SELF__.words %}
{{WordoftheDayfromDB}} # this output below object
["{\"id\":4,\"word_tr\":\"parazit\",\"slug_tr\":\"parazit\",\"word_gr\":\"\\u03c0\\u03b1\\u03c1\\u03ac\\u03c3\\u03b9\\u03c4\\u03bf\",\"slug_gr\":\"parasito\",\"pubordraft\":1,\"created_at\":\"2017-06-07 13:04:57\",\"updated_at\":\"2017-06-07 13:04:57\",\"deleted_at\":null,\"word_image\":\"\\\/cropped-images\\\/image2.jpg\",\"typeswb_id\":0}"]
can someone tell me a way to extract keys and values from the about twig variable.
what i already tried is following:
<pre> {{WordoftheDayfromDB.id}}</pre>
or
{% for item in WordoftheDayfromDB %}
{{item.word_tr}}
{% endfor %}
also some combination using {% if WordoftheDayfromDB is iterable %}.
I will appreciate your answer very much!
thank you for reading my question.
You can use the for loop so that the keys and values are both accessible like this:
{% for key, value in WordoftheDayfromDB %}
<li>{{ key }}: {{ value }}</li>
{% endfor %}
So the answer is rather complex then even i anticipated! i had to do a lot of digging with frustration to really get at the bottom of this matter.
First thing first, i was doing a cron job where i saved the data from a model in text type field. That is why if you see above result i.e
{% set WordoftheDayfromDB = __SELF__.words %}
{{WordoftheDayfromDB}} # this output below object
["{\"id\":4,\"word_tr\":\"parazit\",\"slug_tr\":\"parazit\",\"word_gr\":\"\\u03c0\\u03b1\\u03c1\\u03ac\\u03c3\\u03b9\\u03c4\\u03bf\",\"slug_gr\":\"parasito\",\"pubordraft\":1,\"created_at\":\"2017-06-07 13:04:57\",\"updated_at\":\"2017-06-07 13:04:57\",\"deleted_at\":null,\"word_image\":\"\\\/cropped-images\\\/image2.jpg\",\"typeswb_id\":0}"]
it outputs a JSON String, too bad can't iterate or do something with it.
To solve this,
Create json_decode filter in twig.
Apply the filter to value part of array.
Access Individual values of array with variable[keyname] method.
I created a twig filter json_decode
for creating filter see this Link
while in October, the creation to new twig extension is rather easy which is just give registerMarkupTags method in Plugin.php with filter array poiting to name and function name. See this link for extending twig in octobercms here
Now, the part we were waiting for, how to get the values and show them in twig template. Here it is going to be, by using above same example. This is what i did
{% set wordoftheday = __SELF__.words %}
{% for key, value in wordoftheday %}
{% set decoded = value|json_decode %}
# to get the indvisual values
{{ decoded['id'] }}
{{ decoded['created_at'] }}
{% endfor %}

Twig Dynamic Variable Assignment

I am trying to dynamically assign variables in Twig inside a loop. For example, this is the JSON being passed into the template:
[{
"name": "firstName",
"value": "Adam",
},
{
"name": "Lastname",
"value": "Human",
}]
It's worth noting, I do not have the ability to modify this JSON formatting, as it's coming from a third party, so I need to solve this problem on the template side.
I want to loop through this json and create variables for each object, like so:
{% for item in json %}
{% set {{item.name}} = item.value %}
{% endfor %}
The challenge is Twig is assumes I'm assigning a value to a literal, when I want to assign the value to a evaluated variable name. This way I can just reference each item in the array like {{firstName}} and get back "Adam" in the template.
I've tried a number of different ways to force Twig to dynamically create a variable array, such as:
{% set (item.name) = item.value %}
and
{% set options = {} %}
{% for item in json %}
{% set options[item.name] = item.value %}
{% endfor %}
With no luck.
Any ideas on dynamically creating variables? This is straight forward in most programming languages, so I'm struggling to understand how this is handled in a template engine like Twig.
If the values are actually iterateable and not a single json string you can put them in an array like:
{% set values = [] %}
{% for item in json %}
{% set values = values|merge({(item.name): item.value}) %}
{% endfor %}
Then you can use values.firstName.
If it is a json string and thus can't be looped through like this. You need to write a basic string parser in twig. I've written something similar like that last week in this answer however. Its a very bad idea in general as it fails on so many occasions.

How to automatically check if variables are not empty in Symfony 3?

(Sorry for this bad english)
I would like to know if it's possible to automatically check if variables from MySQL request are not empty in Symfony 3. I know that I can put {% if foo is defined %} in Twig or something like this but I didn't find if there's a way to do it automatically. I can test the request in the controller too. But with those solutions I have to do it for every request.
All my website uses "if not empty then show it" that's why I'm trying to find it.
Edit : I know how to check every fields of every request in Twig or in php (Controller) one by one but there is a lot of duplication code, which is "boring". Thats why I am asking you if something automatic exists to check my data. (parameter in Symfony, ...)
Thank you <3
If I understand, your problem :
You want to iterate on each property in an entity. But you can't, then you are searching for a solution to not write :
{% if entity.property1 %}
{{ entity.property1 }}
{% endif %}
{% if entity.property2 %}
{{ entity.property2 }}
{% endif %}
{% if entity.property3 %}
{{ entity.property3 }}
{% endif %}
You have two solutions to make your properties traversable :
Get your entity with a Doctrine query using ->getArrayResult() instead of ->getResult()
Use ReflectionClass to get the properties as an array :
http://php.net/manual/fr/class.reflectionclass.php
So you can iterate on each property, and do something like that :
{# Where you get your entity as an array #}
{% for property in entity %}
{% if not property is null %}
{{ property }}
{% endif %}
{% endfor %}
{# where fields comes from the ReflectionClass #}
{% for field in fields %}
{% if not attribute(entity,field) is null %}
{{ attribute(entity,field)}}
{% endif %}
{% endfor %}
Use the Twig strict_variables config parameter and set it to false (should be the default value):
strict_variables boolean
If set to false, Twig will silently ignore invalid variables
(variables and or attributes/methods that do not exist) and replace
them with a null value. When set to true, Twig throws an exception
instead (default to false).

How to check whether array element is defined or not in twig file?

I am trying to access array but it is not getting accessed.
in my config.yml following is my array :
abc : [xyz]
and in another file i am writing following code to access abc array.
{% if abc[0] is defined) %}
then do something
{% endif %}
but somehow its not working. please help me out i am newbie in this.
It depends if the variable is always declared or not:
If the variable is always declared and the array can be empty
{% if abc is not empty %}
{# then do something #}
{% endif %}
<variable> is not empty in Twig is equivalent to !empty($variable) in PHP. When an array is provided, is not empty will check there is a value and/or a value in the array.
empty test in Twig documentation.
If the variable is not always declared
Check that the abc variable is declared and not empty:
{% if (abc is declared) and (abc is not empty) %}
{# then do something #}
{% endif %}
<variable> is declared in Twig is equivalent to isset($variable) in PHP.
defined test in Twig documentation.
Based on comments I would recommend using foreach loop instead and define your ifs based on index values. Something like this:
{% for abcs in abc %}
{% if (loop.index == 0) %}
then do something
{% endif %}
{% endfor %}
BR's

Categories