JSON object tree recursion with underline and base

Let's say I have a json object with nested arrays to unknown depths. I want to pass each array to the _.template function. For example, my json object might look like this:

$start_elements = array ( array( "elementTag"=>"li", "elementClass"=>"dashboard", "elementContent"=>array( "elementTag"=>"a", "elementContent"=>"Dashboard", "href"=>"#home" ) ), array( "elementTag"=>"li", "elementClass"=>"count indicator", "elementContent"=>array( array( "elementTag"=>"span", "elementClass"=>"data-count='8'", "elementContent"=>"Notifications" ), array( "elementTag"=>"ul", "elementClass"=>" ", "elementContent"=>array( "elementTag"=>"li", "elementContent"=>array( "elementTag"=>"a", "href"=>"#", "elementExtra"=>"data-modal", "elementContent"=>array( array( "elementTag"=>"h4", "elementContent"=>"Lorem Ipsum" ), array( "elementTag"=>"<p>", "elementContent"=>"Lorem ipsum dolor sit imet smd ddm lksdm lkdsm" ) ) ) ) ) ) ) ); json_encode($start_elements); 
.

_ pattern:

 _.template('<<%= elementTag %> class="<%= elementClass %>" href="<%= href %>"><%= elementContent %></<%= elementTag %>') 

The nested structure of arrays is significant, because I want to output html to the same nested structure. For example, the above object will output the li object with an anchor tag inside it. How can I apply a template to each nested array while maintaining this structure?

+4
source share
2 answers

I would make a wrapper function around your template so that your template is painless. You can then use the methods of the underscore utility to check if you have an array, object (or string) ( _.isArray and _.isObject ) in your hands.

You will need to pass your shell into the template so that you can use it. You can simply _.extend your data using {tmpl: tmpl} .

Here an albeit simplified example works:

  var data = { elementTag: "li", elementContent: [{ elementTag: "a", elementContent: "Dashboard" }, { elementTag: "div", elementContent: "Hello" }] }; var tmpl = _.template('<<%= elementTag %>><%= template(elementContent) %></<%= elementTag %>>'); function template(elData) { var html = ""; if (_.isArray(elData)) { _.each(elData, function (el) { html += template(el); }); } else if (_.isObject(elData)) { html = tmpl(_.extend({ template: template }, elData)); } else { html = elData; } return html; } console.log(template(data)); 
+1
source

You can do the following:

  function applyTemplate (obj) {
   if _.has (obj, "elementContent") {
      obj.elementContent = applyTemplate (obj.elementContent)
   }
   return _.template ("templateString", obj)
 }

Basically you look at the whole tree and replace elementContent with your template value going from bottom to top.

0
source

All Articles