简体   繁体   中英

What is the best way to handle variable JSON data in Symfony using twig?

For a project I need to show on a website the JSON result of a particular PHP call. For this, a Symfony project including a corresponding html.twig page is already setup.

Automatically I wanted to start converting the JSON object into PHP objects sothat I can use them for the implementation of the output form. What I did not think about and ran into was that in the render function, which is used to copy PHP variables to the html.twig page sothat they can be used there, cannot handle objects. Only strings and string arrays. (correct me if I am wrong)

After this, I wanted to do the same in Javascript, but Twig does not work with Javascript...

What is a nice and clean way to convert variable JSON data into an HTML page? I prefer not to use Javascript as confident information is involved in the JSON data.

MyController.php

public function handleJSON(): Response
{
   return $this->render('output.html.twig', [ 'variable1' => 'value', 'variable2' => 'value2' ]);
}

output.html.twig

<div> Variable 1 </div>
<p>{{ variable1 }}</p>
<div> Variable 2 </div>
<p>{{ variable2 }}</p>

On Symfony you can pass php object on your render. And in twig you can use for exemple the method getName() equal in twig {{ var.name }} . Twig test if there are the method getName on your php class. If you don't want to use an ascessor but a simple method use its name, Look the doc template . So for you controller convert the json to php object and render

public function handleJSON(): Response
{
   return $this->render('output.html.twig', ['phpObject' => $obj]);
}

In your twig

<div>{{ phpObject.name }}{# for getName #}</div>
<p>{{ phpObject.translation("en"){# for the method translation(string $val) #} }}</p>

And you can use js on twig but twig render html code for the client, and you can import js file and css on your twig by the webpack

I'm sorry for my english

You cold use JSON_PRETTY_PRINT:

<pre>{{ article|json_encode(constant('JSON_PRETTY_PRINT')) }}</pre>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM