Wednesday, July 24, 2013

Generate UI from JSON

I received some feedback that my previous minimal post was a little too minimal. So here's an ever-so-slightly extended version.

It shows how to use Metawidget as a lightweight, no-fuss solution to quickly render JSON objects on the client. This extended version also saves the JSON object back again. Here's the entire code:

<!DOCTYPE HTML>
<html>
   <head>
      <script src="http://metawidget.org/js/3.4/metawidget-core.min.js"></script>
      <style>
         #metawidget {
            border: 1px solid #cccccc;
            width: 250px;
            border-radius: 10px;
            padding: 10px;
            margin: 50px auto;
         }
         #metawidget button {
            display: block;
            margin: 10px auto 0px;
         }
      </style>
   </head>
   <body>
      <div id="metawidget">
         <button onclick="save()">Save</button>
      </div>
      <script type="text/javascript">
         var mw = new metawidget.Metawidget( document.getElementById( 'metawidget' ));
         mw.toInspect = {
            firstname: 'Homer',
            surname: 'Simpson',
            age: 36
         };
         mw.buildWidgets();
         function save() {
            mw.getWidgetProcessor(
               function( widgetProcessor ) {
                  return widgetProcessor instanceof metawidget.widgetprocessor.SimpleBindingProcessor;
               }
            ).save( mw );
            console.log( mw.toInspect );
         }

      </script>
   </body>
</html>

This will handily render:

Clicking the Save button will update the original JSON object, and print the results to the console.

Of course Metawidget can extend this further to support form validation, alternate layouts, third-party components, and much more. To see how, the best place to start is the tutorial.

0 comments: