Dust.js输出JSON密钥 [英] Dust.js output JSON key

查看:92
本文介绍了Dust.js输出JSON密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 dust.js ,是否可以输出JSON密钥?

With dust.js, is it possible to output the JSON key ?

即如何输出密钥name和profile而不在我的模板中对其进行硬编码?

i.e. How do I output the key "name" and "profile" without hard-coding them in my template?

{
name: "Foo",
profile: {
           name: "Bar"
         }
}

最终文本,JSON密钥名称和配置文件没有条形码。

Final text, JSON key name and profiles not barcoded.

name Foo
profile - name - Bar


推荐答案

确定你可以。定义一个这样的部分:

sure you can. define a section like so:

{@keyvalue:cont}
  {key} - {value}
{/keyvalue}

然后重新定义JSON上下文,如下所示:

then redefine the JSON context like so:

cont:{
    name: "Foo",
    profile: "Bar" //I'm simplifying this a bit for the sake of this example
}

这是为了使上面的keyvalue部分的上下文受到约束只有'续'。那么你可以像这样定义keyvalue助手:

this is so that the context for the keyvalue section above gets constrained to only 'cont'. then you can define the keyvalue helper like this:

"keyvalue": function(chunk, context, bodies){
  var items = context.current(), //this gets the current context hash from the Context object (which has a bunch of other attributes defined in it)
      ctx;

  for (key in items) {
    ctx = {"key" : key, "value" : items[key]};
    chunk = chunk.render(bodies.block, context.push(ctx));
  }

  return chunk
}

应该做的伎俩。在dustjs网站上测试了这个。希望你可以添加到这个以进入嵌套哈希。

should do the trick. tested this on the dustjs website. hopefully you can add on to this to get into nested hashes.

如果您需要在上下文中定义HTML标记属性,这是特别有用的 - 我不希望必须定义一组属性,然后它们对应单独键中的值集。我喜欢他们在一起。更易于阅读,更易于管理。

this is particularly useful if for example you need to define HTML tag attributes in your context - i wouldn't want to have to define a set of attributes and THEN their corresponding set of values in separate keys. I'd like them together. easier to read, easier to manage.

这篇关于Dust.js输出JSON密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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