Parse an existing JSON string in fluid template?

丶灬走出姿态 提交于 2019-11-29 18:09:46

As an alternative to using a custom ViewHelper, you could use a transient property in your model. Let's assume your model has a property "jsonData" that is a JSON encoded string.

Now, you add another property $jsonArray and a getter for it:

/**
 * @var array
 * @transient
 */
protected $jsonArray;

And in the getter, you decode the data:

/**
 * @return array
 */
public function getJsonArray() {
  return json_decode($this->jsonData);
}

A transient property is like a virtual property. You don't need a DB field and TCA definition for it and you cannot do queries based on it, but you have the data available in your object:

<f:for each="{item.jsonArray}" as="value">
 {value}
</f:for>

Yes you need to use own viewhelper or decode your JSON string in the controller (I prefer the last), depends which is more comfortable for you.

There is no way to decode JSON in Fluid, sorry

In Fluid standalone and TYPO3v8 and up:

$this->view->assign('json', new \TYPO3Fluid\Fluid\Variables\JSONVariableProvider('path/to/my/fileOrUrl.json'));
// then in Fluid:
{json.any.path.inside.jsonfile}

See also the ChainedVariableProvider which will allow you to use for example a JSON file as base variables and variables from another array to overlay those. Using this VariableProvider causes Fluid to look for a (non-NULL) variable in the normal array first, then the JSON file (or vice versa if you order it thusly).

<script type="text/javascript">
  var json = '{f:format.htmlentitiesDecode(value:your_value)}';
  var your_value = jQuery.parseJSON(json);
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!