使用JSON中的JS生成HTML页面

rd4*_*d42 8 html javascript parsing json

我正在寻找一个使用Javascript来解析JSON文件并输出html文件或填充html文件的基本示例.到目前为止我找到的所有示例都有代码片段,我没有背景填写之间的空白.

感谢任何小提琴(这将是很棒的),链接和智能的评论.

小智 14

您可以使用微模型库(如Mustache)使用{{ key }}模板语法将传入的JSON对象解析为HTML片段.如果你的对象是这样的:

var myObj = {
    name: 'Joe Smith',
    age: 25,
    features: {
        hairColor: 'red',
        eyeColor: 'blue'
    }
};
Run Code Online (Sandbox Code Playgroud)

使用Mustache,您可以使用{{#}}和{{/}}轻松地将其呈现为HTML以遍历嵌套对象:

Mustache.render('Hello, my name is {{name}} and I am {{age}} years old. {{#features}} I have {{hairColor}} hair and {{eyeColor}} eyes.{{/features}}', myObj);
Run Code Online (Sandbox Code Playgroud)

哪个输出:

你好,我叫Joe Smith,今年25岁.我有红头发和蓝眼睛.

编辑:更多germane应用程序 - 使用具有嵌套对象列表的模板动态生成控制面板.这是我的模板和对象(为了清晰起见,HTML分为列表并加入):

var panel = [
  '<div id="cpanel">',
    '{{#cpanel}}',
      '<div class="panel_section">',
        '<h1 class="cpanel">{{name}}</h1>',
        '<p>',
          '{{#content}}',
            '<button id="{{id}}">{{id}}</button>',
          '{{/content}}',
        '</p>',
      '</div>',
    '{{/cpanel}}',
  '</div>',
].join('\n');

var panelObj = {
  cpanel: [
  {
    name: 'playback',
    content: [
      {id: 'play'},
      {id: 'pause'},
      {id: 'stop'}
    ]
  }, {
    name: 'zoom',
    content: [
      {id: 'zoomIn'},
      {id: 'zoomOut'}
    ]
  }]
};
Run Code Online (Sandbox Code Playgroud)

然后用Mustache渲染:

Mustache.render(panel, panelObj);
Run Code Online (Sandbox Code Playgroud)

哪个输出:

<div id="cpanel">
  <div class="panel_section">
    <h1 class="cpanel">playback</h1>
    <p>
      <button id="play">play</button>
      <button id="pause">pause</button>
      <button id="stop">stop</button>
    </p>
  </div>
  <div class="panel_section">
    <h1 class="cpanel">zoom</h1>
    <p>
      <button id="zoomIn">zoomIn</button>
      <button id="zoomOut">zoomOut</button>
    </p>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)


Pri*_*osK 14

模板的例子

我建议使用模板工具,例如PURE ......

这种工具的目的是分离逻辑和表示.

例如,使用提到的工具从JSON数据生成列表如下所示:

JSON数据文件

{'who':'BeeBole!'}
Run Code Online (Sandbox Code Playgroud)

HTML文件

<html>

<head>
  <title>PURE Unobtrusive Rendering Engine</title>

  <script src="../libs/jquery.js"></script>
  <script src="../libs/pure.js"></script>
</head>

<body>
  <!-- the HTML template -->
  Hello <a class="who" href="#"></a>

  <script>
    // the JSON data we want to render
    $.getJSON('yourJSONdataFile.json', function(data) {
        // run the rendering
        $('a').autoRender(data);
        // PURE tries to match class with the JSON property and replace the node value with the value of the JSON property
    });
  </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果您有简单的JSON数据,这是最基本的方法(请参阅那里的 JSFiddle示例).如果基本方法不合适,入门指南将引导您通过另一个示例.有关更多高级功能,请查看文档.

备择方案

在上面的例子中没有使用PURE的特殊原因.你有很多选择:

...或者您可以按照那里的说明手动完成.