问题
With dust.js, is it possible to output the JSON key ?
i.e. How do I output the key "name" and "profile" without hard-coding them in my template?
{
name: "Foo",
profile: {
name: "Bar"
}
}
Final text, JSON key name and profiles not barcoded.
name Foo
profile - name - Bar
回答1:
sure you can. define a section like so:
{@keyvalue:cont}
{key} - {value}
{/keyvalue}
then redefine the JSON context like so:
cont:{
name: "Foo",
profile: "Bar" //I'm simplifying this a bit for the sake of this example
}
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
}
should do the trick. tested this on the dustjs website. hopefully you can add on to this to get into nested hashes.
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.
回答2:
The method below is almost the same as @asyraf9's answer, but without redefining the JSON and a usage example.
dust.helpers.iterate = function(chunk, context, bodies, params) {
params = params || {};
var obj = params['on'] || context.current();
for (var k in obj) {
chunk = chunk.render(bodies.block, context.push({key: k, value: obj[k]}));
}
return chunk;
}
Source: https://github.com/rashad612/dustjs-helpers/commit/9039130dc060a4bf3e93856601891a7da9047bac
Use it in the template like:
{#myobject.myarray}
{@iterate on=.}
{key} - {value}
{/iterate}
{/myobject.myarray}
It displays all keys and values of objects inside an array.
回答3:
Dust doesn't have this functionality built in because philosophically, JSON should never have data in a key. Consider changing your data model to something like:
{
name: "Foo",
profile: {
fields: [
{
title: "name",
value: "Bar"
}
]
}
}
来源:https://stackoverflow.com/questions/10564997/dust-js-output-json-key