解析流体模板中的现有JSON字符串? [英] Parse an existing JSON string in fluid template?

查看:92
本文介绍了解析流体模板中的现有JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON字符串,其中包含一些我想在模板中呈现的数据.因为Fluid数组也是用JSON表示的,所以我想我可能只需要将该JSON字符串并将其移交给Fluid,告诉它像对待其他数组一样对待它,并在模板中使用它.

I have a JSON string with some data I want to render in a template. As Fluid arrays are notated in JSON too, I thought I might just take that JSON string and hand it over to fluid, telling it to treat it just like some other array and use it in the template.

因此获得了很大的速度,并且减少了开销(不必将JSON数据拆分以将其保存在数据库中,就可以轻松地将其模板化为流畅的模板).

Thus gaining a lot of speed and losing overhead (don't have to split the JSON data up to save it in the DB, can template it easily in fluid).

这是行不通的,至少不是我尝试过的方式.

It wouldn't work, at least not how I tried it.

<f:alias map="{item.jsonData}">
  {fieldname}
</f:alias>

它-当然-抱怨它收到了一个字符串,而不是一个数组.

It - of course - complained it had received a string, not an array.

在将数组恢复为流体之前,我是否必须构建一个viewhelper并执行json_decode?还是有一种更原生的方式?

Do I have to build a viewhelper and do json_decode before returning the array to fluid? Or is there a more native way?

这是基本的控制器操作:

Here's the basic controller action:

/**
 * action show
 *
 * @param \NAMESPACE\Myext\Domain\Model\Item $item
 * @return void
 */
public function showAction(\NAMESPACE\Myext\Domain\Model\Item $item) {
    $this->view->assign('item', $item);
}

推荐答案

作为使用自定义ViewHelper的替代方法,您可以在模型中使用过渡属性.假设您的模型具有一个属性"jsonData",它是一个JSON编码的字符串.

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.

现在,您添加另一个属性$ jsonArray和它的一个吸气剂:

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

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

然后在getter中,对数据进行解码:

And in the getter, you decode the data:

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

瞬时属性就像虚拟属性.您不需要它的数据库字段和TCA定义,也不能基于它进行查询,但是您的对象中有可用的数据:

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>

这篇关于解析流体模板中的现有JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆