0

I´ve the following presets in my db stored as LONGTEXT:

[
    {
        "timewindow": "21:00-24:00",
        "mas": "2"
    },
    {
        "timewindow": "00:00-02:00",
        "mas": "2"
    },
    {
        "timewindow": "02:00-04:00",
        "mas": "2"
    }
]

I pass this JSON String to my TWIG3-Template and try to iterate over it, like this:

{% set presets = service.preset|json_encode|raw %}
{% for preset in presets %}
<tr id="{{service.shortname}}_shift_{{loop.index}}">
    <td><input type="text" name="{{service.shortname}}_timewindow_{{loop.index}}" value="{{preset.timewindow}}" required></td>
    <td><input type="number" name="{{service.shortname}}_amountma_{{loop.index}}" value="{{preset.mas}}" required></td>
</tr>
<input type="hidden" name="{{service.shortname}}_id_{{loop.index}}" value="{{service.id}}" required>
{% endfor %}

Unfortunately there is no output. When I display the variable {{presets}} it shows an escaped view of the JSON like this:

[{\"timewindow\": \"21:00-24:00\", \"mas\": \"2\"},{\"timewindow\": \"00:00-02:00\", \"mas\": \"2\"},{\"timewindow\": \"02:00-04:00\", \"mas\": \"2\"}]

Maybe there is the problem? So my question is, how can I translate a JSON string into a usable TWIG object.

DarkBee
  • 16,592
  • 6
  • 46
  • 58
meDom
  • 183
  • 1
  • 1
  • 8
  • You are using the wrong function, `json_encode` is to transform an object into `JSON`. See the answer above on how to add `json_decode` to `twig` as it isn't included by default – DarkBee Apr 06 '22 at 05:55

1 Answers1

0

Thx DarkBee, I knew that article you mentioned, but I thought I couldn´t use it, as I use TWIG standalone. This is how I solved my problem:

I added the marked line to my index.php:

$app = AppFactory::create();
$twig = Twig::create('../application/view/', ['cache' => false]);
// add start
$twig->addExtension(new Application\TwigExtension);
// add end
$app->add(TwigMiddleware::create($app, $twig));

And at least I put a TwigExtension.php in my core model:

<?php
namespace Application;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class TwigExtension extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            new TwigFunction('jsonDecode', [$this, 'jsonDecode']),
        ];
    }

    public function jsonDecode($string)
    {
        return json_decode($string);
    }
}

Now I can use this line for decoding JSON:

{% set presets = jsonDecode(service.preset) %}
meDom
  • 183
  • 1
  • 1
  • 8
  • Just an FYI, you can short-circuit/chain known functions, e.g. `new TwigFunction('jsonDecode', 'json_decode')`, which will make the code a lil bit shorter – DarkBee Apr 08 '22 at 06:55