Reputation: 3678
When working with Mustache, or any templating engine, a properly structured JSON object is needed to render some specific template. Generally (I believe), a developer knows their application's data model, and how they want to show data in a template, but find that their data model doesn't perfectly output JSON in the form their templates expect. So we often need to write data processing functions that transform data model outputs into acceptable mustache template inputs.
For example, @Liang's application outputs a JSON array like:
"prop":{"brands":["nike","adidas","puma"]}
but his template expects it to be in the form:
"brands":[{"name":"nike"},{"name":"adidas"},{"name":"puma"}]
so he needs to transform it via:
var data = {brands: obj.prop['brands'].map(function(x){ return {name: x}; })};
Liang also could have tweaked his template to get it working without a data transformation step. But what if I don't know what the template is before hand and my only template guarantee is that its tags resolve to keys in my data model. Is it possible to write a function bridge(data_model, template)
which takes as input the data model and mustache template and outputs the transformation function Transform
. Such that Transform
itself is the code which massages the data model outputs into acceptable mustache template inputs.
Said another way, if
data_model = "prop":{"brands":["nike","adidas","puma"]}
and
template = {{#brands}}
<b>{{name}}</b>
{{/brands}}
then what bridge
produces the javascript
{brands: obj.prop['brands'].map(function(x){ return {name: x}; })}
= bridge(data_model, template)
(the output of bridge
would be javascript code).
I understand that this may be too unconstrained to give a good answer, but I think everyone can recognize that at a minimum, bridge
would need to be able to output nested for loops
or map
commands. How could I go about making perhaps a crude version of bridge
that has for loop
commands in the right places respective to mustache tags?.. sorry if this doesn't make great sense, it's a challenging question for me to articulate. Honestly, it feels a bit like asking for magic.
Upvotes: 1
Views: 1652
Reputation: 41
It isn't in javascript but R3M (written in php) can template json files as well. it syntax is borrowed from Smarty but different. it will reach production stability in 2023. It enables templates which can be used in .js, .json & .tpl.
{
"books": "{json.select($url, 'book')}"
}
see https://github.com/like-it/r3m-framework
Upvotes: 2