簡體   English   中英

使用 twig 處理 Symfony 中的變量 JSON 數據的最佳方法是什么?

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

對於一個項目,我需要在網站上顯示特定 PHP 調用的 JSON 結果。 為此,已經設置了包含相應html.twig頁面的 Symfony 項目。

我想自動開始將 JSON object 轉換為 PHP 對象,以便我可以使用它們來實現 Z714E6221F6391F3D。 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. 只有字符串和字符串 arrays。 (如果我錯了請糾正我)

在此之后,我想在 Javascript 中做同樣的事情,但是 Twig 不適用於 Javascript...

將變量 JSON 數據轉換為 HTML 頁面的好方法是什么? 我不喜歡使用 Javascript,因為 JSON 數據中包含有信心的信息。

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>

在 Symfony 上,您可以在渲染上傳遞 php object。 在 twig 中,您可以使用方法getName() equal in twig {{ var.name }} Twig 測試您的 php class 上是否有方法 getName。 如果您不想使用 ascessor,而是使用簡單的方法,請使用其名稱,請查看 doc 模板 所以對你來說 controller 將 json 轉換為 php ZA8CFDE6331BD59EB2AC96F8911C4B66Z 並渲染

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

在你的 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

我很抱歉我的英語

你冷使用 JSON_PRETTY_PRINT:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM