我正在寻找像{{json JSON-flat-definition}}这样的余烬帮助函数来定义属性或参数。在哪里找到以及如何使用?

问题描述 投票:0回答:1

Ember中的内置辅助函数(通过把手)已经定义,例如{{let}},{{array}},{{hash}},所以对我来说,{{json}的基础}助手,接受任何json字符串作为参数来定义模板的属性或组件的参数。有这样的帮手吗? json-definition-string的样子如何,因为内置仅使用空格来构造数据?

https://guides.emberjs.com/release/components/helper-functions/#toc_the-let-helperhttps://guides.emberjs.com/release/components/helper-functions/#toc_the-array-helperhttps://guides.emberjs.com/release/components/helper-functions/#toc_the-hash-helper

所以应该是类似的东西

<Greeting @people={{json
    firstName='Tom'
    lastName='Dale'

    firstName='Yehuda'
    lastName='Katz'

    firstName='Jen'
    lastName='Weber'
  }} />
function templates ember.js helper
1个回答
0
投票

没有。您需要自己调用arrayhash。因此,您可以这样做:

@people={{array
  (hash
    firstName='Tom'
    lastName='Dale'
  )
  (hash
    firstName='Yehuda'
    lastName='Katz'
  )
  (hash
    firstName='Jen'
    lastName='Weber'
  )
}}

请谨慎考虑“ json字符串”,因为您将其用于“由数组和字典组成的递归数据结构”,而不是JSON。因为JSON序列化格式,或者用其名称“ JavaScript Object Notation”表示。如果具有相同结构的相同数据,但格式不同,则不再JSON

因此,如果您这样做

const foo = {
  name: "something"
};

这是not一个JSON对象foo绝对不是JSON Object,而只是Object。您可能会争辩说,从{}source code部分是JSON Object,但是那是错误的。 JSON定义有效Javascript对象表示法的subset

{
  name: "something"
}

不是有效的JSON,因为name不在双引号中。

因此,如果您构建一个json助手,它将像这样使用:

  <MyComponent @data={{json "[{ \"firstName\": \"Tom\" }]"}} />

那绝不是好用的,如果您在JSON中有一个实际的string值并想对其进行解析,则基本上会非常有用。这个帮手也很容易写:

import { helper } from '@ember/component/helper';

export default helper(function json([json]/*, hash*/) {
  return JSON.parse(json);
});

这里要提到的一件事是,有一个RFC proposed引入了一个简单的语法来定义数组和散列到余烬中。

所以也许某天这样的东西[[可能成为余烬的一部分:

RFC
但是目前您必须如上所述在每个级别上调用@people={{[
  (
    firstName='Tom'
    lastName='Dale'
  )
  (
    firstName='Yehuda'
    lastName='Katz'
  )
  (
    firstName='Jen'
    lastName='Weber'
  )
]}}
 / array
© www.soinside.com 2019 - 2024. All rights reserved.