0

I have a collection passed from a controller action and added to the view from a variable which I can iterate through for all of the articles in a blog. Each article has its own JSONB column stored in a PostgreSQL table.

I am wondering how to iterate through each article in the blog while JSON decoding each piece of data stored in that specific JSONB column for neat display on a Twig template page. Does anyone have any idea about how to do this? Would it be done in the Controller action and stored into a variable or in a Twig template itself? Could it be done both ways? If so, I would be interested to see how it could be done both ways!

It is easy for me to figure out how to do so on each individual article show page since one article is selected and you can json_decode that one column from the table in the controller then pass a variable (for this example I will call it decoded).

To print a data attribute in a Twig template I can do something like this:

{{decoded['title']}}

Or this:

{{decoded['body']}}

So, how can you achieve something similar with an entire blog collection on a blog index page as opposed to one specific article from the blog table on a show page?

If I were trying to do the same thing with a typical textbook collection in a Twig template the variable passed by the controller to the view (Twig template) would be accessed and iterated through each column in the table like this:

{% for article in blog %}
{article.title}
{article.body}
{% endfor %}

So...I can access the newly added JSON column now similarly by adding it to a similar loop structure on a Twig template page and calling:

{article.json_data}

...but my problem is that there is no json_decode filter for Twig template variable output, only json_encode which can be called in a similar iteration loop like this:

{article.json_data | json_encode}

...but I need json_decode not json_encode, thus my question!

Thank you for any and all help offered!

DarkBee
  • 16,592
  • 6
  • 46
  • 58
finiteloop
  • 483
  • 4
  • 14
  • Some more code would be helpful. It's unclear what you have now and what you are trying to do. – Matias Kinnunen Feb 01 '18 at 04:42
  • @martias No problem. Sorry, I am going off memory so please forgive me. I just updated my question with a little bit more detail so you can possibly understand what I am trying to do a little bit better! – finiteloop Feb 01 '18 at 04:55
  • 4
    Possible duplicate of [Decoding JSON in Twig](https://stackoverflow.com/questions/14500698/decoding-json-in-twig) – DarkBee Feb 01 '18 at 06:27

0 Answers0